package com.jumi.microservice.service.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.base.dto.ExportExcelCommonResponse;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.constant.DelFlag;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.common.page.TableDataInfo;
import com.jumi.microservice.common.utils.DateUtil;
import com.jumi.microservice.common.utils.EnumUtil;
import com.jumi.microservice.constant.PayChannelEnum;
import com.jumi.microservice.constant.compensation.AfterSaleStatusEnum;
import com.jumi.microservice.constant.reissue.ImportFlagEnum;
import com.jumi.microservice.domain.GoodsInfoDTO;
import com.jumi.microservice.domain.OrderWarehouseInfoDTO;
import com.jumi.microservice.domain.SupplyStockDeductDTO;
import com.jumi.microservice.domain.TransferWarehouseDTO;
import com.jumi.microservice.dto.admin.*;
import com.jumi.microservice.dto.excel.ImportNoSelfResponse;
import com.jumi.microservice.dto.invoice.InvoiceOrderSnListRequest;
import com.jumi.microservice.dto.invoice.InvoiceOrderSnListResponse;
import com.jumi.microservice.dto.logistics.AutoSpiltRequest;
import com.jumi.microservice.dto.order.DeliverGoodsRequest;
import com.jumi.microservice.dto.order.OrderLogRequest;
import com.jumi.microservice.dto.reponse.FenXiaoReponse;
import com.jumi.microservice.dto.reponse.JmUserReponse;
import com.jumi.microservice.entity.LogisticsGoods;
import com.jumi.microservice.entity.OrderGoods;
import com.jumi.microservice.entity.OrderLogistics;
import com.jumi.microservice.entity.UserOrder;
import com.jumi.microservice.enumerate.*;
import com.jumi.microservice.enums.FenXiaoType;
import com.jumi.microservice.enums.Level;
import com.jumi.microservice.mapper.LogisticsGoodsMapper;
import com.jumi.microservice.mapper.OrderGoodsMapper;
import com.jumi.microservice.mapper.OrderLogisticsMapper;
import com.jumi.microservice.mapper.UserOrderMapper;
import com.jumi.microservice.material.dto.supplier.JmSupplierResponse;
import com.jumi.microservice.material.dto.warehouse.JmWarehouseResponse;
import com.jumi.microservice.material.service.IJmSupplierService;
import com.jumi.microservice.material.service.IJmWarehouseService;
import com.jumi.microservice.service.*;
import com.jumi.microservice.service.logistics.AutoSpiltService;
import com.jumi.microservice.service.logistics.admin.RelocateService;
import com.jumi.microservice.service.logistics.admin.SendService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wangjingdao
 */
@Service
public class AllOrderServiceImpl {
    private static final Logger log = LoggerFactory.getLogger(AllOrderServiceImpl.class);
    @Resource
    UserOrderMapper userOrderMapper;
    @Resource
    OrderGoodsMapper orderGoodsMapper;
    @DubboReference
    IJmSupplierService iJmSupplierService;
    @DubboReference
    IJmWarehouseService iJmWarehouseService;
    @DubboReference
    IMemberService iMemberService;
    @DubboReference
    OrderInventoryApi iInventoryService;
    @Resource
    SendService sendService;
    @DubboReference
    IWalletInvoiceService walletInvoiceService;
    @Resource
    AutoSpiltService autoSpiltService;
    @DubboReference
    IFenXiaoService iFenXiaoService;
    @DubboReference
    private IOrderDubboService orderDubboService;
    @Resource
    LogisticsGoodsMapper logisticsGoodsMapper;
    @Resource
    OrderLogisticsMapper orderLogisticsMapper;
    @DubboReference
    IOrderInventoryService iOrderInventoryService;

    /**
     * 订单查询
     *
     * @param request
     * @return
     */
    public TableDataInfo<OrderAllResponse> getOrderAll(FindOrderRequest request) {
        TableDataInfo<OrderAllResponse> tableDataInfo = new TableDataInfo<>();
        List<OrderAllResponse> orderAllResponses = new ArrayList<>();
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.orderBy(true, false, "create_time");
        if ((request.getPhoneType() == PhoneTypeEnum.BUYER.getCode())) {
            ResponseResult<Integer> uid = iMemberService.getUidByMobile(request.getPhone());
            if (uid != null) {
                userOrderQueryWrapper.eq("buyer_id", uid.getData());
            } else {
                return tableDataInfo;
            }
        } else if (request.getPhoneType() == PhoneTypeEnum.SELLER.getCode()) {
            userOrderQueryWrapper.eq("receiver_phone", request.getPhone());
        }
        if (request.getOrderNo() != null) {
            userOrderQueryWrapper.eq("order_no", request.getOrderNo());
        }
        if (request.getOrderStatus() != null) {
            userOrderQueryWrapper.eq("order_status", request.getOrderStatus());
        }
        if (request.getStartTime() != null && request.getEndTime() != null) {
            userOrderQueryWrapper.between("create_time", request.getStartTime(), request.getEndTime());
        }
        if (request.getPayStartTime() != null && request.getPayEndTime() != null) {
            userOrderQueryWrapper.between("pay_time", request.getPayStartTime(), request.getPayEndTime());
        }
        IPage<UserOrder> userOrderPage = new Page<>(request.getPageNum(), request.getPageSize());
        userOrderPage = userOrderMapper.selectPage(userOrderPage, userOrderQueryWrapper);
        if (userOrderPage.getRecords().size() == 0) {
            return tableDataInfo;
        }
        Map<Long, JmUserReponse> userMap = getUserInfoMap(userOrderPage.getRecords().stream().map(o -> o.getBuyerId().intValue()).collect(Collectors.toList()));
        for (UserOrder record : userOrderPage.getRecords()) {
            OrderAllResponse orderAllResponse = new OrderAllResponse();
            BeanUtils.copyProperties(record, orderAllResponse);
            orderAllResponse.setOrderAmount(record.getPayAmount());
            if (userMap.containsKey(record.getBuyerId())) {
                orderAllResponse.setPhone(userMap.get(record.getBuyerId()).getMobile());
                orderAllResponse.setNickName(userMap.get(record.getBuyerId()).getName());
            }
            OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(record.getOrderStatus(), OrderStatusEnum.class);
            orderAllResponse.setOrderStatusString(orderStatusEnum.getMessage());
            orderAllResponse.setPayType(EnumUtil.getByCode(record.getPayType(), PayChannelEnum.class).getDescription());
            orderAllResponse.setPromotionAmount(new BigDecimal(0));
            orderAllResponse.setServiceAmount(new BigDecimal(0));
            List<FenXiaoReponse> fenXiaoReponses = iFenXiaoService.getSumFenxiao(record.getOrderNo(), record.getBuyerId().intValue(), null);
            fenXiaoReponses.forEach(
                    fenXiao -> {
                        if (fenXiao.getType().equals(FenXiaoType.推广收益)) {
                            orderAllResponse.setPromotionAmount(fenXiao.getYongjin());
                        } else if (fenXiao.getType().equals(FenXiaoType.服务收益)) {
                            orderAllResponse.setServiceAmount(fenXiao.getYongjin());
                        }
                    }
            );
            orderAllResponses.add(orderAllResponse);
        }
        tableDataInfo.setTotal(userOrderPage.getTotal());
        tableDataInfo.setRows(orderAllResponses);
        return tableDataInfo;
    }

    /**
     * 获取所有用户信息
     *
     * @param userIds， ，  慕课
     * @return
     */
    public Map<Long, JmUserReponse> getUserInfoMap(List<Integer> userIds) {
        List<JmUserReponse> list = iMemberService.getMemberByUids(userIds).getData();
        Map<Long, JmUserReponse> map = new HashMap<>(list.size());
        for (JmUserReponse jmUserReponse : list) {
            map.put(jmUserReponse.getId().longValue(), jmUserReponse);
        }
        return map;
    }

    /**
     * 所有订单
     *
     * @param request
     * @returndfdsafdsafdsa
     */
    public TableDataInfo<OrderGoodsAllResponse> goodsOrderAll(OrderGoodsRequest request) {
        TableDataInfo<OrderGoodsAllResponse> orderGoodsAllResponseTableDataInfo = new TableDataInfo<>();
        List<OrderGoodsAllResponse> orderGoodsAllResponses = new ArrayList<>();
        boolean b = false;
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        if (request.getType() != null && request.getType().equals(SupplierTypeEnum.SUPPLIER.getCode())) {
            orderGoodsQueryWrapper.eq("supplier_id", request.getSupplier());
            b = true;
        } else if (request.getType() != null && request.getType().equals(SupplierTypeEnum.DELIVERY_WAREHOUSE.getCode())) {
            orderGoodsQueryWrapper.eq("real_warehouse", request.getSupplier());
            b = true;
        }
        if (request.getGoodsName() != null) {
            orderGoodsQueryWrapper.like("goods_name", request.getGoodsName());
            b = true;
        }
        List<Integer> orderId = null;
        if (b) {
            orderGoodsQueryWrapper.orderByDesc("id");
            //订单商品信息
            List<OrderGoods> goods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
            orderId = goods.stream().map(OrderGoods::getOrderId).collect(Collectors.toList());
            if (orderId.size() == 0) {
                return orderGoodsAllResponseTableDataInfo;
            }
        }

        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        if (request.getOrderNo() != null) {
            userOrderQueryWrapper.like("order_no", request.getOrderNo());
        }
        if (request.getStartTime() != null && request.getEndTime() != null) {
            //下单时间
            userOrderQueryWrapper.between("create_time", request.getStartTime(), request.getEndTime());
        }
        if (request.getStartPayTime() != null && request.getEndPayTime() != null) {
            userOrderQueryWrapper.between("pay_time", request.getStartPayTime(), request.getEndPayTime());
        }
        if (request.getPayNo() != null) {
            userOrderQueryWrapper.eq("pay_no", request.getPayNo());
        }
        if (request.getPhoneType() == PhoneTypeEnum.BUYER.getCode()) {
            ResponseResult<Integer> uid = iMemberService.getUidByMobile(request.getPhone());
            if (uid != null) {
                userOrderQueryWrapper.eq("buyer_id", uid.getData());
            } else {
                userOrderQueryWrapper.eq("buyer_id", 0);
            }
        } else if (request.getPhoneType() == PhoneTypeEnum.SELLER.getCode()) {
            userOrderQueryWrapper.eq("receiver_phone", request.getPhone());
        }
        userOrderQueryWrapper.orderByDesc("id");
        if (orderId != null) {
            userOrderQueryWrapper.in("id", orderId);
        }
        IPage<UserOrder> userOrderIPage = new Page<>(request.getPageNum(), request.getPageSize());
        userOrderIPage = userOrderMapper.selectPage(userOrderIPage, userOrderQueryWrapper);
        List<Integer> orderIds = userOrderIPage.getRecords().stream().map(UserOrder::getId).collect(Collectors.toList());
        if (orderIds.size() == 0) {
            return orderGoodsAllResponseTableDataInfo;
        }
        userOrderIPage.getRecords().forEach(
                userOrder -> {
                    UserDetailsResponse userDetailsResponse = new UserDetailsResponse();
                    OrderGoodsAllResponse orderGoodsAllResponse = new OrderGoodsAllResponse();
                    BeanUtils.copyProperties(userOrder, orderGoodsAllResponse);
                    orderGoodsAllResponse.setCreateTime(DateUtil.getTime(userOrder.getCreateTime()));
                    if (userOrder.getPayTime() != null) {
                        orderGoodsAllResponse.setPayTime(DateUtil.getTime(userOrder.getPayTime()));
                    }
                    PayChannelEnum payChannelEnum = EnumUtil.getByCode(userOrder.getPayType(), PayChannelEnum.class);
                    orderGoodsAllResponse.setPayType(payChannelEnum.getDescription());
                    OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(userOrder.getOrderStatus(), OrderStatusEnum.class);
                    orderGoodsAllResponse.setOrderStatusString(orderStatusEnum.getMessage());
//                    }
                    orderGoodsAllResponse.setPayAmount(userOrder.getPayAmount());
                    userDetailsResponse.setAddress(userOrder.getReceiverAddress());
                    userDetailsResponse.setPhone(userOrder.getReceiverPhone());
                    userDetailsResponse.setNickName(userOrder.getReceiverName());
                    orderGoodsAllResponse.setUser(userDetailsResponse);
                    orderGoodsAllResponses.add(orderGoodsAllResponse);
                }
        );
        //获取全部供应商
        List<JmSupplierResponse> jmSupplierResponses = getSupply();
        Map<Integer, JmSupplierResponse> supplyMap = jmSupplierResponses.stream().collect(Collectors.toMap(s -> s.getSupplierId().intValue(), s -> s));
        //获取全部发货仓
        ResponseResult<List<JmWarehouseResponse>> iJmWarehouseServiceAll = iJmWarehouseService.findAll();
        Map<Integer, JmWarehouseResponse> warehouseMap = iJmWarehouseServiceAll.getData().stream().collect(Collectors.toMap(s -> s.getWarehouseId().intValue(), s -> s));
        orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.in("order_id", orderIds);
        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        for (OrderGoodsAllResponse orderGoodsAllResponse : orderGoodsAllResponses) {
            List<OrderGoodsResponse> orderGoodsResponses = new ArrayList<>();
            for (OrderGoods record : orderGoods) {
                if (orderGoodsAllResponse.getId().equals(record.getOrderId())) {
                    OrderGoodsResponse orderGoodsResponse = new OrderGoodsResponse();
                    //根据商品id 获取商品名称
                    LogisticsStatusEnum logisticsStatusEnum = EnumUtil.getByCode(record.getGoodsStatus(), LogisticsStatusEnum.class);
                    AfterSaleStatusEnum afterSaleStatusEnum = EnumUtil.getByCode(record.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
                    BeanUtils.copyProperties(record, orderGoodsResponse);
                    orderGoodsResponse.setSelfFlag(record.getSelfFlag());
                    orderGoodsResponse.setAfterSealStatus(record.getAfterSealStatus());
                    orderGoodsResponse.setSelfFlag(record.getSelfFlag());
                    if (record.getSelfFlag() == SelfFlagEnum.YES_SELF.getCode()) {
                        if (warehouseMap.containsKey(record.getRealWarehouse())) {
                            orderGoodsResponse.setSupplierId(record.getRealWarehouse());
                            orderGoodsResponse.setSupplierName(warehouseMap.get(record.getRealWarehouse()).getWarehouseName());
                        }
                    } else if (record.getSelfFlag() == SelfFlagEnum.NO_SELF.getCode()) {
                        orderGoodsResponse.setSupplierId(record.getSupplierId());
                        if (supplyMap.containsKey(record.getSupplierId())) {
                            orderGoodsResponse.setSupplierName(supplyMap.get(record.getSupplierId()).getSupplierCompanyName());
                        }
                    }
                    orderGoodsResponse.setAfterSealStatusString(afterSaleStatusEnum.getMsg());
                    orderGoodsResponse.setGoodsStatusString(logisticsStatusEnum.getMsg());
                    orderGoodsResponses.add(orderGoodsResponse);
                }
            }
            orderGoodsAllResponse.setOrderGoodsResponses(orderGoodsResponses);
        }
        orderGoodsAllResponseTableDataInfo.setRows(orderGoodsAllResponses);
        orderGoodsAllResponseTableDataInfo.setTotal(userOrderIPage.getTotal());
        return orderGoodsAllResponseTableDataInfo;
    }


    public OrderDetailsResponse getOrderDetails(OrderDetailsRequest request) throws Exception {
        OrderDetailsResponse orderDetailsResponse = new OrderDetailsResponse();
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.eq("id", request.getId());
        ;
        UserOrder userOrder = userOrderMapper.selectOne(userOrderQueryWrapper);
        if (userOrder == null) {
            return new OrderDetailsResponse();
        }
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("order_id", request.getId());
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        List<OrderGoodsDetailsResponse> orderGoodsDetailsResponses = new ArrayList<>();
        //供应商
        List<JmSupplierResponse> jmSupplierResponses = getSupply();
        //获取全部发货仓
        ResponseResult<List<JmWarehouseResponse>> iJmWarehouseServiceAll = iJmWarehouseService.findAll();
        List<JmWarehouseResponse> jmWarehouseResponses = iJmWarehouseServiceAll.getData();
        for (OrderGoods orderGood : orderGoods) {
            OrderGoodsDetailsResponse orderGoodsDetailsResponse = new OrderGoodsDetailsResponse();
            BeanUtils.copyProperties(orderGood, orderGoodsDetailsResponse);
            orderGoodsDetailsResponse.setId(orderGood.getId());
//            if (orderGood.getSelfFlag() == SelfFlagEnum.YES_SELF.getCode()) {
            if (orderGood.getSelfFlag() == SelfFlagEnum.YES_SELF.getCode()) {
                orderGoodsDetailsResponse.setRealWarehouse(orderGood.getRealWarehouse());
                for (JmWarehouseResponse jmWarehouseResponse : jmWarehouseResponses) {
                    if (orderGood.getRealWarehouse().equals(jmWarehouseResponse.getWarehouseId().intValue())) {
                        orderGoodsDetailsResponse.setRealWarehouseName(jmWarehouseResponse.getWarehouseName());
                    }
                }

            } else if (orderGood.getSelfFlag() == SelfFlagEnum.NO_SELF.getCode()) {
                orderGoodsDetailsResponse.setRealWarehouse(orderGood.getShouldWarehouse());
                for (JmSupplierResponse jmSupplierResponse : jmSupplierResponses) {
                    if (orderGood.getSupplierId().equals(jmSupplierResponse.getSupplierId().intValue())) {
                        orderGoodsDetailsResponse.setRealWarehouseName(jmSupplierResponse.getSupplierCompanyName());
                    }
                }
            }
//            }
            String logisticsOrderNo = sendService.realLogisticsNo(orderGood.getOrderId(), orderGood.getGoodsId());
            orderGoodsDetailsResponse.setLogisticsOrder(logisticsOrderNo);
            orderGoodsDetailsResponse.setTotal(orderGood.getGoodsPrice().multiply(new BigDecimal(orderGood.getGoodsAmount())));
            orderGoodsDetailsResponses.add(orderGoodsDetailsResponse);
        }
        ResponseResult<JmUserReponse> memberByUid = iMemberService.getMemberByUid(userOrder.getBuyerId().intValue());
        if (memberByUid.getData() == null) {
            throw new Exception("查不到用户信息uid是" + userOrder.getBuyerId());
        }
        JmUserReponse user = memberByUid.getData();
        orderDetailsResponse.setOrderGoodsDetailsResponse(orderGoodsDetailsResponses);
        OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(userOrder.getOrderStatus(), OrderStatusEnum.class);
        orderDetailsResponse.setOrderStatusString(orderStatusEnum.getMessage());
        orderDetailsResponse.setOrderNo(userOrder.getOrderNo());
        orderDetailsResponse.setNickName(user.getName());
        orderDetailsResponse.setPhone(user.getMobile());
        orderDetailsResponse.setLevel(Level.getLevelByValue(userOrder.getBuyerRole()).getDesc());
        BeanUtils.copyProperties(userOrder, orderDetailsResponse);
        orderDetailsResponse.setIsPay(userOrder.getPayTime() == null ? 0 : (byte) 1);
        orderDetailsResponse.setConfirmTime(null);
        if (userOrder.getOrderStatus().equals(OrderStatusEnum.COMPLETED.getCode())) {
            orderDetailsResponse.setConfirmTime(DateUtil.format(userOrder.getConfirmTime(), "yyyy-MM-dd HH:mm:ss"));
        }
        PayChannelEnum payChannelEnum = EnumUtil.getByCode(userOrder.getPayType(), PayChannelEnum.class);
        orderDetailsResponse.setPayType(payChannelEnum.getDescription());
        //订单信息
        //收发货信息
        //发票信息
        InvoiceOrderSnListRequest invoiceOrderSnListRequest = new InvoiceOrderSnListRequest();
        invoiceOrderSnListRequest.setOrderNum(userOrder.getOrderNo());
        TableDataInfo<InvoiceOrderSnListResponse> invoiceOrderSnListResponseTableDataInfo = walletInvoiceService.invoiceListOrder(invoiceOrderSnListRequest);
        if (invoiceOrderSnListResponseTableDataInfo.getRows() != null && invoiceOrderSnListResponseTableDataInfo.getRows().size() != 0) {
            List<InvoiceOrderSnListResponse> invoiceOrderSnListResponse = invoiceOrderSnListResponseTableDataInfo.getRows();
            List<OrderSnListResponse> orderSnListResponse = new ArrayList<>();
            invoiceOrderSnListResponse.forEach(
                    invoiceOrderSn -> {
                        OrderSnListResponse snListResponse = new OrderSnListResponse();
                        BeanUtils.copyProperties(invoiceOrderSn, snListResponse);
                        orderSnListResponse.add(snListResponse);
                    }
            );
            orderDetailsResponse.setOrderSnListResponse(orderSnListResponse);
        }
        return orderDetailsResponse;
    }

    public TableDataInfo<NonSelfOperatedListResponse> getNonSelfOperated(NonSelfOperatedRequest request) {
        TableDataInfo<NonSelfOperatedListResponse> nonSelfOperatedListResponseTableDataInfo = new TableDataInfo<>();
        List<NonSelfOperatedListResponse> nonSelfOperatedListResponses = new ArrayList<>();
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        orderGoodsQueryWrapper.eq("self_flag", 0);
        orderGoodsQueryWrapper.eq("goods_status", LogisticsStatusEnum.WAIT_SEND.getCode());
        orderGoodsQueryWrapper.eq("is_import", ImportFlagEnum.IMPORT_FLAG_NO.getCode());
        if (request.getType() != null && request.getType().equals(SupplierTypeEnum.SUPPLIER.getCode())) {
            orderGoodsQueryWrapper.eq("supplier_id", request.getSupplierId());
        } else if (request.getType() != null && request.getType().equals(SupplierTypeEnum.DELIVERY_WAREHOUSE.getCode())) {
            orderGoodsQueryWrapper.eq("real_warehouse", request.getSupplierId());
        }
        if (request.getGoodsName() != null) {
            orderGoodsQueryWrapper.like("goods_name", request.getGoodsName());
        }
        orderGoodsQueryWrapper.orderByDesc("id");
        IPage<OrderGoods> orderGoodsPage = new Page<>(request.getPageNum(), request.getPageSize());
        orderGoodsPage = orderGoodsMapper.selectPage(orderGoodsPage, orderGoodsQueryWrapper);
        List<Integer> goodsId = orderGoodsPage.getRecords().stream().map(OrderGoods::getOrderId).collect(Collectors.toList());
        //剔除部分发货的订单id
        if (goodsId.size() == 0) {
            return nonSelfOperatedListResponseTableDataInfo;
        }
        QueryWrapper<OrderGoods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.in("order_id", goodsId);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(goodsQueryWrapper);
        for (OrderGoods orderGood : orderGoods) {
            if (!orderGood.getGoodsStatus().equals(LogisticsStatusEnum.WAIT_SEND.getCode())&&orderGood.getGoodsStatus().equals(LogisticsStatusEnum.CANCEL.getCode())&&orderGood.getGoodsStatus().equals(LogisticsStatusEnum.UN_PAY.getCode())) {
                goodsId.remove(orderGood.getOrderId());
            }
        }
        //供应商
        List<JmSupplierResponse> jmSupplierResponses = getSupply();
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        if (request.getStartPayTime() != null && request.getEndPayTime() != null) {
            userOrderQueryWrapper.between("pay_time", request.getStartPayTime(), request.getEndPayTime());
            //支付时间
        }
        if (request.getStartTime() != null && request.getEndTime() != null) {
            //下单时间
            userOrderQueryWrapper.between("create_time", request.getStartTime(), request.getEndTime());
        }
        if (request.getPhoneType() == PhoneTypeEnum.BUYER.getCode()) {
            ResponseResult<Integer> uid = iMemberService.getUidByMobile(request.getPhone());
            if (uid.getData() != null) {
                userOrderQueryWrapper.eq("buyer_id", uid.getData());
            }
            //根据购买人获取手机号加进去
        } else if (request.getPhoneType() == PhoneTypeEnum.SELLER.getCode()) {
            userOrderQueryWrapper.eq("receiver_phone", request.getPhone());
        }
        userOrderQueryWrapper.orderByDesc("id");
        List<UserOrder> orders = userOrderMapper.selectList(userOrderQueryWrapper);
//        IPage<UserOrder> userOrderIPage = new Page<>(request.getPageNum(), request.getPageSize());
//        userOrderIPage = userOrderMapper.selectPage(userOrderIPage, userOrderQueryWrapper);
//        List<UserOrder> orders = userOrderMapper.selectList(userOrderQueryWrapper);
        List<Integer> userId = orders.stream().map(UserOrder::getId).collect(Collectors.toList());
        List<Integer> orderId = goodsId.stream().filter(userId::contains).collect(Collectors.toList());
        if (orderId.size() == 0) {
            return nonSelfOperatedListResponseTableDataInfo;
        }
        userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.in("id", orderId);
        userOrderQueryWrapper.orderByDesc("id");
        List<UserOrder> userOrderList = userOrderMapper.selectList(userOrderQueryWrapper);
        userOrderList.forEach(
                userOrder -> {
                    NonSelfOperatedListResponse nonSelfOperatedListResponse = new NonSelfOperatedListResponse();
                    BeanUtils.copyProperties(userOrder, nonSelfOperatedListResponse);
                    nonSelfOperatedListResponse.setCreateTime(DateUtil.getTime(userOrder.getCreateTime()));
                    if (userOrder.getPayTime() != null) {
                        nonSelfOperatedListResponse.setPayTime(DateUtil.getTime(userOrder.getPayTime()));
                    }
                    PayChannelEnum payChannelEnum = EnumUtil.getByCode(userOrder.getPayType(), PayChannelEnum.class);
                    nonSelfOperatedListResponse.setPayType(payChannelEnum.getDescription());
                    OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(userOrder.getOrderStatus(), OrderStatusEnum.class);
                    nonSelfOperatedListResponse.setOrderStatusString(orderStatusEnum.getMessage());
                    UserDetailsResponse userDetailsResponse = new UserDetailsResponse();
                    userDetailsResponse.setNickName(userOrder.getReceiverName());
                    userDetailsResponse.setPhone(userOrder.getReceiverPhone());
                    userDetailsResponse.setAddress(userOrder.getReceiverAddress());
                    nonSelfOperatedListResponse.setUser(userDetailsResponse);
                    nonSelfOperatedListResponses.add(nonSelfOperatedListResponse);
                }
        );
        orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.in("order_id", orderId);
        orderGoodsQueryWrapper.orderByDesc("id");
        List<OrderGoods> goods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        for (NonSelfOperatedListResponse operatedListResponse : nonSelfOperatedListResponses) {
            List<NonSelfOperatedResponse> nonSelfOperatedResponses = new ArrayList<>();
            for (OrderGoods record : goods) {
                if (operatedListResponse.getId().equals(record.getOrderId())) {
                    NonSelfOperatedResponse nonSelfOperatedResponse = new NonSelfOperatedResponse();
                    //根据商品id 获取商品名称
                    BeanUtils.copyProperties(record, nonSelfOperatedResponse);
                    for (JmSupplierResponse jmSupplierResponse : jmSupplierResponses) {
                        if (record.getSupplierId() != null) {
                            if (record.getSupplierId().equals(jmSupplierResponse.getSupplierId().intValue())) {
                                nonSelfOperatedResponse.setSupplierName(jmSupplierResponse.getSupplierCompanyName());
                            }
                        }
                    }
                    nonSelfOperatedResponses.add(nonSelfOperatedResponse);
                }
            }
            operatedListResponse.setNonSelfOperatedResponses(nonSelfOperatedResponses);
        }
        nonSelfOperatedListResponseTableDataInfo.setRows(nonSelfOperatedListResponses);
        nonSelfOperatedListResponseTableDataInfo.setTotal(orderGoodsPage.getTotal());
        return nonSelfOperatedListResponseTableDataInfo;
    }

    public TableDataInfo<PartialResponse> getPartial(PartialRequest request) {
        TableDataInfo<PartialResponse> partialResponseTableDataInfo = getPartialShipment(request);
        return partialResponseTableDataInfo;
    }

    public TableDataInfo<PartialResponse> getGoodsReceived(GoodsReceivedRequest request) {
        List<PartialResponse> partialResponses = new ArrayList<>();
        TableDataInfo<PartialResponse> tableDataInfo = new TableDataInfo<>();
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        if (request.getType() != null && request.getType().equals(SupplierTypeEnum.SUPPLIER.getCode())) {
            orderGoodsQueryWrapper.eq("supplier_id", request.getSupplierId());
        } else if (request.getType() != null && request.getType().equals(SupplierTypeEnum.DELIVERY_WAREHOUSE.getCode())) {
            orderGoodsQueryWrapper.eq("real_warehouse", request.getSupplierId());
        }
        if (request.getGoodsName() != null) {
            orderGoodsQueryWrapper.like("goods_name", request.getGoodsName());
        }
        orderGoodsQueryWrapper.and(
                queryWrapper -> queryWrapper.eq("goods_status", LogisticsStatusEnum.WAIT_RECEIVE.getCode()).or().eq("goods_status", LogisticsStatusEnum.PART_SEND.getCode())
        );
        if (request.getLogisticsNo() != null && !request.getLogisticsNo().isEmpty()) {
            QueryWrapper<LogisticsGoods> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("real_logistics_no", request.getLogisticsNo()).eq("del_flag", 0);
            List<LogisticsGoods> list = logisticsGoodsMapper.selectList(queryWrapper);
            List<Integer> orderIds = list.stream().map(LogisticsGoods::getOrderId).collect(Collectors.toList());
            if (orderIds.isEmpty()) {
                tableDataInfo.setTotal(0L);
                tableDataInfo.setRows(partialResponses);
                return tableDataInfo;
            }
            orderGoodsQueryWrapper.in("order_id", orderIds);
        }
        orderGoodsQueryWrapper.orderByDesc("id");
        List<OrderGoods> orderGoodsPage = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        List<Integer> goodsId = orderGoodsPage.stream().map(OrderGoods::getOrderId).collect(Collectors.toList());
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
//        userOrderQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        if (request.getPhoneType() == PhoneTypeEnum.BUYER.getCode()) {
            ResponseResult<Integer> uid = iMemberService.getUidByMobile(request.getPhone());
            if (uid != null) {
                userOrderQueryWrapper.eq("buyer_id", uid.getData());
            } else {
                tableDataInfo.setTotal(0L);
                tableDataInfo.setRows(partialResponses);
                return tableDataInfo;
            }
            //根据手机号获取uid 加进去
        } else if (request.getPhoneType() == PhoneTypeEnum.SELLER.getCode()) {
            userOrderQueryWrapper.eq("receiver_phone", request.getPhone());
        }
        if (request.getStartTime() != null && request.getEndTime() != null) {
            userOrderQueryWrapper.between("create_time", request.getStartTime(), request.getEndTime());
        }
        if (!goodsId.isEmpty()) {
            userOrderQueryWrapper.in("id", goodsId);
        }
        userOrderQueryWrapper.orderByDesc("id");
        List<UserOrder> orders = userOrderMapper.selectList(userOrderQueryWrapper);
        List<Integer> userId = orders.stream().map(UserOrder::getId).collect(Collectors.toList());
        List<Integer> orderId = userId.stream().filter(goodsId::contains).collect(Collectors.toList());
        if (orderId.size() == 0) {
            return tableDataInfo;
        }
        //获取全部供应商
        List<JmSupplierResponse> jmSupplierResponses = getSupply();
        //获取全部发货仓
        ResponseResult<List<JmWarehouseResponse>> iJmWarehouseServiceAll = iJmWarehouseService.findAll();
        List<JmWarehouseResponse> jmWarehouseResponses = iJmWarehouseServiceAll.getData();
        userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.in("id", orderId);
        userOrderQueryWrapper.orderByDesc("create_time");
        IPage<UserOrder> userOrderPage = new Page<>(request.getPageNum(), request.getPageSize());
        userOrderPage = userOrderMapper.selectPage(userOrderPage, userOrderQueryWrapper);
        orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.in("order_id", orderId);
        orderGoodsQueryWrapper.orderByDesc("create_time");
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        userOrderPage.getRecords().forEach(
                userOrder -> {
                    PartialResponse partialResponse = new PartialResponse();
                    BeanUtils.copyProperties(userOrder, partialResponse);
                    partialResponse.setCreateTime(DateUtil.getTime(userOrder.getCreateTime()));
                    if (userOrder.getPayTime() != null) {
                        partialResponse.setPayTime(DateUtil.getTime(userOrder.getPayTime()));
                    }
                    PayChannelEnum payChannelEnum = EnumUtil.getByCode(userOrder.getPayType(), PayChannelEnum.class);
                    partialResponse.setPayType(payChannelEnum.getDescription());
                    OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(userOrder.getOrderStatus(), OrderStatusEnum.class);
                    partialResponse.setOrderStatusString(orderStatusEnum.getMessage());
                    UserDetailsResponse userDetailsResponse = new UserDetailsResponse();
                    userDetailsResponse.setAddress(userOrder.getReceiverAddress());
                    userDetailsResponse.setPhone(userOrder.getReceiverPhone());
                    userDetailsResponse.setNickName(userOrder.getReceiverName());
                    partialResponse.setUser(userDetailsResponse);
                    partialResponses.add(partialResponse);
                }
        );
        for (PartialResponse partialResponse : partialResponses) {
            List<PartialOneResponse> partialOneResponses = new ArrayList<>();
            for (OrderGoods orderGood : orderGoods) {
                if (partialResponse.getId().equals(orderGood.getOrderId())) {
                    PartialOneResponse partialOneResponse = new PartialOneResponse();
                    LogisticsStatusEnum logisticsStatusEnum = EnumUtil.getByCode(orderGood.getGoodsStatus(), LogisticsStatusEnum.class);
                    BeanUtils.copyProperties(orderGood, partialOneResponse);
                    AfterSaleStatusEnum afterSaleStatusEnum = EnumUtil.getByCode(orderGood.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
                    partialOneResponse.setAfterSealStatusString(afterSaleStatusEnum.getMsg());
                    partialOneResponse.setLogisticsOrderNo(sendService.realLogisticsNo(orderGood.getOrderId(), orderGood.getGoodsId()));
                    if (orderGood.getSelfFlag() == SelfFlagEnum.YES_SELF.getCode()) {
                        if (orderGood.getRealWarehouse() != null) {
                            partialOneResponse.setSupplierId(orderGood.getRealWarehouse());
                            for (JmWarehouseResponse jmWarehouseResponse : jmWarehouseResponses) {
                                if (orderGood.getRealWarehouse().equals(jmWarehouseResponse.getWarehouseId().intValue())) {
                                    partialOneResponse.setSupplierName(jmWarehouseResponse.getWarehouseName());
                                }
                            }
                        }
                    } else if (orderGood.getSelfFlag() == SelfFlagEnum.NO_SELF.getCode()) {
                        if (orderGood.getSupplierId() != null) {
                            partialOneResponse.setSupplierId(orderGood.getSupplierId());
                            for (JmSupplierResponse jmSupplierResponse : jmSupplierResponses) {
                                if (orderGood.getSupplierId().equals(jmSupplierResponse.getSupplierId().intValue())) {
                                    partialOneResponse.setSupplierName(jmSupplierResponse.getSupplierCompanyName());
                                }
                            }
                        }
                    }
                    partialOneResponse.setGoodsStatusString(logisticsStatusEnum.getMsg());
                    partialOneResponses.add(partialOneResponse);
                }
            }
            partialResponse.setPartialOneResponses(partialOneResponses);
        }
        tableDataInfo.setRows(partialResponses);
        tableDataInfo.setTotal(userOrderPage.getTotal());
        return tableDataInfo;
    }


    public TableDataInfo<CompletedResponse> getCompletedList(CompletedRequest request) {
        TableDataInfo<CompletedResponse> tableDataInfo = new TableDataInfo<>();
        List<CompletedResponse> completedResponses = new ArrayList<>();
        boolean b = false;
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        if (request.getType() != null && request.getType().equals(SupplierTypeEnum.SUPPLIER.getCode())) {
            b = true;
            orderGoodsQueryWrapper.eq("supplier_id", request.getSupplierId());
        } else if (request.getType() != null && request.getType().equals(SupplierTypeEnum.DELIVERY_WAREHOUSE.getCode())) {
            b = true;
            orderGoodsQueryWrapper.eq("real_warehouse", request.getSupplierId());
        }
        if (request.getGoodsName() != null) {
            b = true;
            orderGoodsQueryWrapper.like("goods_name", request.getGoodsName());
        }
        if (request.getLogisticsNo() != null && !request.getLogisticsNo().isEmpty()) {
            b = true;
            QueryWrapper<LogisticsGoods> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("del_flag", 0).eq("real_logistics_no", request.getLogisticsNo());
            List<LogisticsGoods> list = logisticsGoodsMapper.selectList(queryWrapper);
            List<Integer> orderIds = list.stream().map(LogisticsGoods::getOrderId).collect(Collectors.toList());
            if (orderIds.isEmpty()) {
                tableDataInfo.setTotal(0L);
                tableDataInfo.setRows(completedResponses);
                return tableDataInfo;
            }
            orderGoodsQueryWrapper.in("order_id", orderIds);
        }
        List<Integer> orderIds = null;
        if (b) {
            orderGoodsQueryWrapper.orderByDesc("id");
            List<OrderGoods> goodsList = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
            if (goodsList.isEmpty()) {
                tableDataInfo.setTotal(0L);
                tableDataInfo.setRows(completedResponses);
                return tableDataInfo;
            }
            orderIds = goodsList.stream().map(OrderGoods::getOrderId).collect(Collectors.toList());
        }

        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        if (request.getStartTime() != null && request.getEndTime() != null) {
            userOrderQueryWrapper.between("create_time", request.getStartTime(), request.getEndTime());
        }
        userOrderQueryWrapper.eq("order_status", OrderStatusEnum.COMPLETED.getCode());
        if (request.getStartTime() != null && request.getEndTime() != null) {
            userOrderQueryWrapper.between("create_time", request.getStartTime(), request.getEndTime());
        }
        if (orderIds != null) {
            userOrderQueryWrapper.in("id", orderIds);
        }
        userOrderQueryWrapper.orderByDesc("id");
        IPage<UserOrder> userOrderPage = new Page<>(request.getPageNum(), request.getPageSize());
        userOrderPage = userOrderMapper.selectPage(userOrderPage, userOrderQueryWrapper);
        List<UserOrder> userOrders = userOrderPage.getRecords();
        orderIds = userOrders.stream().map(UserOrder::getId).collect(Collectors.toList());
        if (orderIds.size() == 0) {
            return tableDataInfo;
        }
        orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.in("order_id", orderIds);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        if (orderGoods.isEmpty()) {
            return tableDataInfo;
        }
        //获取全部供应商
        List<JmSupplierResponse> jmSupplierResponses = getSupply();
        Map<Integer, JmSupplierResponse> supplierMap = jmSupplierResponses.stream().collect(Collectors.toMap(s -> s.getSupplierId().intValue(), s -> s));
        //获取全部发货仓
        List<JmWarehouseResponse> iJmWarehouseServiceAll = iJmWarehouseService.findAll().getData();
        Map<Integer, JmWarehouseResponse> warehouseMap = iJmWarehouseServiceAll.stream().collect(Collectors.toMap(s -> s.getWarehouseId().intValue(), s -> s));
        Map<Integer, List<CompletedGoodsResponse>> orderGoodsMap = new HashMap<>();
        for (OrderGoods orderGoods1 : orderGoods) {
            CompletedGoodsResponse completedGoodsResponse = new CompletedGoodsResponse();
            BeanUtils.copyProperties(orderGoods1, completedGoodsResponse);
            LogisticsStatusEnum logisticsStatusEnum = EnumUtil.getByCode(orderGoods1.getGoodsStatus(), LogisticsStatusEnum.class);
            completedGoodsResponse.setGoodsStatusString(logisticsStatusEnum != null ? logisticsStatusEnum.getMsg() : "");
            AfterSaleStatusEnum afterSaleStatusEnum = EnumUtil.getByCode(orderGoods1.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
            completedGoodsResponse.setAfterSealStatusString(afterSaleStatusEnum != null ? afterSaleStatusEnum.getMsg() : "");
            if (orderGoods1.getSelfFlag() == SelfFlagEnum.YES_SELF.getCode()) {
                if (warehouseMap.containsKey(orderGoods1.getRealWarehouse())) {
                    completedGoodsResponse.setSupplierName(warehouseMap.get(orderGoods1.getRealWarehouse()).getWarehouseName());
                }
            } else {
                if (supplierMap.containsKey(orderGoods1.getSupplierId())) {
                    completedGoodsResponse.setSupplierName(supplierMap.get(orderGoods1.getSupplierId()).getSupplierCompanyName());
                }
            }
            if (orderGoodsMap.containsKey(orderGoods1.getOrderId())) {
                orderGoodsMap.get(orderGoods1.getOrderId()).add(completedGoodsResponse);
            } else {
                List<CompletedGoodsResponse> ll = new ArrayList<>();
                ll.add(completedGoodsResponse);
                orderGoodsMap.put(orderGoods1.getOrderId(), ll);
            }
        }
        userOrders.forEach(
                userOrder -> {
                    CompletedResponse completedResponse = new CompletedResponse();
                    OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(userOrder.getOrderStatus(), OrderStatusEnum.class);
                    BeanUtils.copyProperties(userOrder, completedResponse);
                    if (userOrder.getPayTime() != null) {
                        completedResponse.setPayTime(DateUtil.getTime(userOrder.getPayTime()));
                    }
                    PayChannelEnum payChannelEnum = EnumUtil.getByCode(userOrder.getPayType(), PayChannelEnum.class);
                    completedResponse.setPayType(payChannelEnum != null ? payChannelEnum.getDescription() : "");
                    completedResponse.setCreateTime(DateUtil.getTime(userOrder.getCreateTime()));
                    UserDetailsResponse userDetailsResponse = new UserDetailsResponse();
                    userDetailsResponse.setNickName(userOrder.getReceiverName());
                    userDetailsResponse.setPhone(userOrder.getReceiverPhone());
                    userDetailsResponse.setAddress(userOrder.getReceiverAddress());
                    completedResponse.setUser(userDetailsResponse);
                    completedResponse.setOrderStatusString(orderStatusEnum.getMessage());
                    if (orderGoodsMap.containsKey(userOrder.getId())) {
                        completedResponse.setCompletedGoodsResponses(orderGoodsMap.get(userOrder.getId()));
                    }
                    completedResponses.add(completedResponse);
                }
        );
//        for (CompletedResponse completedResponse : completedResponses) {
//            List<CompletedGoodsResponse> completedGoodsResponses = new ArrayList<>();
//            for (OrderGoods orderGood : orderGoods) {
//                if (completedResponse.getId().equals(orderGood.getOrderId())) {
//                    CompletedGoodsResponse completedGoodsResponse = new CompletedGoodsResponse();
//                    BeanUtils.copyProperties(orderGood, completedGoodsResponse);
//                    LogisticsStatusEnum logisticsStatusEnum = EnumUtil.getByCode(orderGood.getGoodsStatus(), LogisticsStatusEnum.class);
//                    completedGoodsResponse.setGoodsStatusString(logisticsStatusEnum.getMsg());
//                    AfterSaleStatusEnum afterSaleStatusEnum = EnumUtil.getByCode(orderGood.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
//                    completedGoodsResponse.setAfterSealStatusString(afterSaleStatusEnum.getMsg());
////                    if (orderGood.getSelfFlag() == SelfFlagEnum.YES_SELF.getCode()) {
////                        if (orderGood.getRealWarehouse() != null) {
////                            completedGoodsResponse.setSupplierId(orderGood.getRealWarehouse());
////                            for (JmWarehouseResponse jmWarehouseResponse : jmWarehouseResponses) {
////                                if (orderGood.getRealWarehouse().equals(jmWarehouseResponse.getWarehouseId().intValue())) {
////                                    completedGoodsResponse.setSupplierName(jmWarehouseResponse.getWarehouseName());
////                                }
////                            }
////                        }
////                    } else if (orderGood.getSelfFlag() == SelfFlagEnum.NO_SELF.getCode()) {
////                        if (orderGood.getSupplierId() != null) {
////                            completedGoodsResponse.setSupplierId(orderGood.getSupplierId());
////                            for (JmSupplierResponse jmSupplierResponse : jmSupplierResponses) {
////                                if (orderGood.getSupplierId().equals(jmSupplierResponse.getSupplierId().intValue())) {
////                                    completedGoodsResponse.setSupplierName(jmSupplierResponse.getSupplierCompanyName());
////                                }
////                            }
////                        }
////                    }
//                    completedGoodsResponses.add(completedGoodsResponse);
//                }
//            }
//            completedResponse.setCompletedGoodsResponses(completedGoodsResponses);
//        }
        tableDataInfo.setRows(completedResponses);
        tableDataInfo.setTotal(userOrderPage.getTotal());
        return tableDataInfo;
    }

    public TableDataInfo<AfterSaleResponse> getAfterSale(CompletedRequest request) {
        TableDataInfo<AfterSaleResponse> tableDataInfo = new TableDataInfo<>();
        List<AfterSaleResponse> afterSaleResponses = new ArrayList<>();
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        orderGoodsQueryWrapper.ne("after_seal_status", 0);
        orderGoodsQueryWrapper.orderByDesc("id");
        if (request.getType() != null && request.getType().equals(SupplierTypeEnum.SUPPLIER.getCode())) {
            orderGoodsQueryWrapper.eq("supplier_id", request.getSupplierId());
        } else if (request.getType() != null && request.getType().equals(SupplierTypeEnum.DELIVERY_WAREHOUSE.getCode())) {
            orderGoodsQueryWrapper.eq("real_warehouse", request.getSupplierId());
        }
        if (request.getGoodsName() != null) {
            orderGoodsQueryWrapper.eq("goods_name", request.getGoodsName());
        }
        List<OrderGoods> goods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        List<Integer> goodsId = goods.stream().map(OrderGoods::getOrderId).collect(Collectors.toList());
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        if (request.getStartTime() != null && request.getEndTime() != null) {
            userOrderQueryWrapper.between("create_time", request.getStartTime(), request.getEndTime());
        }
        userOrderQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        if (request.getStartTime() != null && request.getEndTime() != null) {

        }
        userOrderQueryWrapper.orderByDesc("id");
        List<UserOrder> userOrders = userOrderMapper.selectList(userOrderQueryWrapper);
        List<Integer> userId = userOrders.stream().map(UserOrder::getId).collect(Collectors.toList());
        List<Integer> orderId = userId.stream().filter(goodsId::contains).collect(Collectors.toList());
        if (orderId.size() == 0) {
            return tableDataInfo;
        }
        //获取全部供应商
        List<JmSupplierResponse> jmSupplierResponses = getSupply();
        //获取全部发货仓
        ResponseResult<List<JmWarehouseResponse>> iJmWarehouseServiceAll = iJmWarehouseService.findAll();
        List<JmWarehouseResponse> jmWarehouseResponses = iJmWarehouseServiceAll.getData();
        userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.in("id", orderId);
        userOrderQueryWrapper.orderByDesc("id");
        IPage<UserOrder> orderPage = new Page<>(request.getPageNum(), request.getPageSize());
        orderPage = userOrderMapper.selectPage(orderPage, userOrderQueryWrapper);
        orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.in("order_id", orderId);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        orderPage.getRecords().forEach(
                userOrder -> {
                    AfterSaleResponse afterSaleGoodsResponse = new AfterSaleResponse();
                    BeanUtils.copyProperties(userOrder, afterSaleGoodsResponse);
                    afterSaleGoodsResponse.setCreateTime(DateUtil.getTime(userOrder.getCreateTime()));

                    if (userOrder.getPayTime() != null) {
                        afterSaleGoodsResponse.setPayTime(DateUtil.getTime(userOrder.getPayTime()));
                    }
                    PayChannelEnum payChannelEnum = EnumUtil.getByCode(userOrder.getPayType(), PayChannelEnum.class);
                    afterSaleGoodsResponse.setPayType(payChannelEnum.getDescription());
                    OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(userOrder.getOrderStatus(), OrderStatusEnum.class);
                    afterSaleGoodsResponse.setOrderStatusString(orderStatusEnum.getMessage());
                    UserDetailsResponse userDetailsResponse = new UserDetailsResponse();
                    userDetailsResponse.setNickName(userOrder.getReceiverName());
                    userDetailsResponse.setPhone(userOrder.getReceiverPhone());
                    userDetailsResponse.setAddress(userOrder.getReceiverAddress());
                    afterSaleGoodsResponse.setUser(userDetailsResponse);
                    afterSaleResponses.add(afterSaleGoodsResponse);
                }
        );
        for (AfterSaleResponse afterSaleResponse : afterSaleResponses) {
            List<AfterSaleGoodsResponse> afterSaleGoodsResponses = new ArrayList<>();
            for (OrderGoods orderGood : orderGoods) {
                if (afterSaleResponse.getId().equals(orderGood.getOrderId())) {
                    AfterSaleGoodsResponse afterSaleGoodsResponse = new AfterSaleGoodsResponse();
                    BeanUtils.copyProperties(orderGood, afterSaleGoodsResponse);
                    AfterSaleStatusEnum afterSaleStatusEnum = EnumUtil.getByCode(orderGood.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
                    afterSaleGoodsResponse.setAfterSealStatusString(afterSaleStatusEnum.getMsg());
                    if (orderGood.getSelfFlag() == SelfFlagEnum.YES_SELF.getCode()) {
                        if (orderGood.getRealWarehouse() != null) {
                            afterSaleGoodsResponse.setSupplierId(orderGood.getRealWarehouse());
                            for (JmWarehouseResponse jmWarehouseResponse : jmWarehouseResponses) {
                                if (orderGood.getRealWarehouse().equals(jmWarehouseResponse.getWarehouseId().intValue())) {
                                    afterSaleGoodsResponse.setSupplierName(jmWarehouseResponse.getWarehouseName());
                                }
                            }

                        }
                    } else if (orderGood.getSelfFlag() == SelfFlagEnum.NO_SELF.getCode()) {
                        afterSaleGoodsResponse.setSupplierId(orderGood.getShouldWarehouse());
                        for (JmSupplierResponse jmSupplierResponse : jmSupplierResponses) {
                            if (orderGood.getSupplierId().equals(jmSupplierResponse.getSupplierId().intValue())) {
                                afterSaleGoodsResponse.setSupplierName(jmSupplierResponse.getSupplierCompanyName());
                            }
                        }

                    }
                    LogisticsStatusEnum logisticsStatusEnum = EnumUtil.getByCode(orderGood.getGoodsStatus(), LogisticsStatusEnum.class);
                    afterSaleGoodsResponse.setGoodsStatusString(logisticsStatusEnum.getMsg());
                    afterSaleGoodsResponses.add(afterSaleGoodsResponse);
                }
            }
            afterSaleResponse.setAfterSaleGoodsResponseList(afterSaleGoodsResponses);
        }
        tableDataInfo.setRows(afterSaleResponses);
        tableDataInfo.setTotal(orderPage.getTotal());
        return tableDataInfo;
    }

    public TableDataInfo<PreSaleResponse> getPreSale(PreSaleRequest request) {
        List<PreSaleResponse> preSaleResponses = new ArrayList<>();
        TableDataInfo<PreSaleResponse> tableDataInfo = new TableDataInfo<>();
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.orderByDesc("id");
        if (request.getType() != null && request.getType().equals(SupplierTypeEnum.SUPPLIER.getCode())) {
            orderGoodsQueryWrapper.eq("supplier_id", request.getSupplierId());
        } else if (request.getType() != null && request.getType().equals(SupplierTypeEnum.DELIVERY_WAREHOUSE.getCode())) {
            orderGoodsQueryWrapper.eq("real_warehouse", request.getSupplierId());
        }
        if (request.getGoodsName() != null) {
            orderGoodsQueryWrapper.eq("goods_name", request.getGoodsName());
        }
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        List<Integer> goodsId = orderGoods.stream().map(OrderGoods::getOrderId).collect(Collectors.toList());
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.eq("order_type", OrderTypeEnum.PRE_SALE_CREATE.getCode());
        userOrderQueryWrapper.eq("order_status", OrderStatusEnum.READY_TO_SHIP.getCode());
        userOrderQueryWrapper.orderByDesc("id");
        if (request.getStartTime() != null && request.getEndTime() != null) {
            userOrderQueryWrapper.between("create_time", request.getStartTime(), request.getEndTime());
        }
        if (request.getPayTime() != null && request.getEndTime() != null) {
            userOrderQueryWrapper.between("pay_time", request.getPayTime(), request.getPayEndTime());
        }
        List<UserOrder> userOrders = userOrderMapper.selectList(userOrderQueryWrapper);
        List<Integer> userId = userOrders.stream().map(UserOrder::getId).collect(Collectors.toList());
        List<Integer> orderId = userId.stream().filter(goodsId::contains).collect(Collectors.toList());
        if (orderId.size() == 0) {
            return tableDataInfo;
        }
        //获取全部供应商
        List<JmSupplierResponse> jmSupplierResponses = getSupply();
        //获取全部发货仓
        ResponseResult<List<JmWarehouseResponse>> iJmWarehouseServiceAll = iJmWarehouseService.findAll();
        List<JmWarehouseResponse> jmWarehouseResponses = iJmWarehouseServiceAll.getData();
        userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.in("id", orderId);
        userOrderQueryWrapper.ne("order_status", OrderStatusEnum.CANCEL.getCode());
        userOrderQueryWrapper.orderByDesc("create_time");
        IPage<UserOrder> orderPage = new Page<>(request.getPageNum(), request.getPageSize());
        orderPage = userOrderMapper.selectPage(orderPage, userOrderQueryWrapper);
        orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.in("order_id", orderId);
        orderGoodsQueryWrapper.orderByDesc("create_time");
        List<OrderGoods> goods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        orderPage.getRecords().forEach(
                userOrder -> {
                    PreSaleResponse preSaleResponse = new PreSaleResponse();
                    BeanUtils.copyProperties(userOrder, preSaleResponse);
                    preSaleResponse.setCreateTime(DateUtil.getTime(userOrder.getCreateTime()));
                    if (userOrder.getPayTime() != null) {
                        preSaleResponse.setPayTime(DateUtil.getTime(userOrder.getPayTime()));
                    }
                    PayChannelEnum payChannelEnum = EnumUtil.getByCode(userOrder.getPayType(), PayChannelEnum.class);
                    preSaleResponse.setPayType(payChannelEnum.getDescription());
                    OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(userOrder.getOrderStatus(), OrderStatusEnum.class);
                    preSaleResponse.setOrderStatusString(orderStatusEnum.getMessage());
                    UserDetailsResponse userDetailsResponse = new UserDetailsResponse();
                    userDetailsResponse.setNickName(userOrder.getReceiverName());
                    userDetailsResponse.setPhone(userOrder.getReceiverPhone());
                    userDetailsResponse.setAddress(userOrder.getReceiverAddress());
                    preSaleResponse.setUser(userDetailsResponse);
                    preSaleResponses.add(preSaleResponse);
                }
        );
        for (PreSaleResponse preSaleResponse : preSaleResponses) {
            List<PreSaleOneResponse> preSaleOneResponses = new ArrayList<>();
            for (OrderGoods orderGood : goods) {
                if (preSaleResponse.getId().equals(orderGood.getOrderId())) {
                    PreSaleOneResponse preSaleOneResponse = new PreSaleOneResponse();
                    BeanUtils.copyProperties(orderGood, preSaleOneResponse);
                    if (orderGood.getSelfFlag() == SelfFlagEnum.YES_SELF.getCode()) {
                        if (orderGood.getRealWarehouse() != null) {
                            preSaleOneResponse.setSupplierId(orderGood.getRealWarehouse());
                            for (JmWarehouseResponse jmWarehouseResponse : jmWarehouseResponses) {
                                if (orderGood.getRealWarehouse().equals(jmWarehouseResponse.getWarehouseId().intValue())) {
                                    preSaleOneResponse.setSupplierName(jmWarehouseResponse.getWarehouseName());
                                }
                            }
                        }
                    } else if (orderGood.getSelfFlag() == SelfFlagEnum.NO_SELF.getCode()) {
                        preSaleOneResponse.setSupplierId(orderGood.getShouldWarehouse());
                        for (JmSupplierResponse jmSupplierResponse : jmSupplierResponses) {
                            if (orderGood.getSupplierId().equals(jmSupplierResponse.getSupplierId().intValue())) {
                                preSaleOneResponse.setSupplierName(jmSupplierResponse.getSupplierCompanyName());
                            }
                        }
                    }
                    preSaleOneResponses.add(preSaleOneResponse);
                }
            }
            preSaleResponse.setPreSaleOneResponse(preSaleOneResponses);
        }
        tableDataInfo.setRows(preSaleResponses);
        tableDataInfo.setTotal(orderPage.getTotal());
        return tableDataInfo;
    }

    /**
     * 备注
     *
     * @param remarkRequest
     * @return
     */
    public ResponseResult<Boolean> setRemark(RemarkRequest remarkRequest) {
        ResponseResult<Boolean> responseResult = new ResponseResult<>();
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        int row = 0;
        if (remarkRequest.getRemark() != null && remarkRequest.getId() != null) {
            UserOrder userOrder = new UserOrder();
            userOrder.setRemark(remarkRequest.getRemark());
            userOrderQueryWrapper.eq("id", remarkRequest.getId());
            row = userOrderMapper.update(userOrder, userOrderQueryWrapper);
        }
        responseResult.setData(row != 0);
        return responseResult;
    }

    public TableDataInfo<ToBeReviewedResponse> getToBeReviewed(ToBeReviewedRequest reviewedRequest) {
        TableDataInfo<ToBeReviewedResponse> toBeReviewedResponseTableDataInfo = new TableDataInfo<>();
        List<ToBeReviewedResponse> reviewedResponses = new ArrayList<>();
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        if (reviewedRequest.getStartTime() != null) {
            orderGoodsQueryWrapper.lt("create_time", reviewedRequest.getStartTime());
        }
        if (reviewedRequest.getRealWarehouse() != null) {
            orderGoodsQueryWrapper.eq("real_warehouse", reviewedRequest.getRealWarehouse());
        }
        if (reviewedRequest.getShouldWarehouse() != null) {
            orderGoodsQueryWrapper.eq("should_warehouse", reviewedRequest.getShouldWarehouse());
        }
        orderGoodsQueryWrapper.eq("verify_status", ExamineEnum.YES_EXAMINE.getCode());
        IPage<OrderGoods> orderGoodsPage = new Page<>(reviewedRequest.getPageNum(), reviewedRequest.getPageSize());
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        List<Integer> orderId = orderGoods.stream().map(OrderGoods::getOrderId).collect(Collectors.toList());
        if (orderId.size() == 0) {
            return toBeReviewedResponseTableDataInfo;
        }
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        userOrderQueryWrapper.in("id", orderId);
        userOrderQueryWrapper.ne("pay_type", PayChannelEnum.NO_PAY.getCode());
        if (reviewedRequest.getReceiverAddress() != null) {
            userOrderQueryWrapper.like("receiver_address", reviewedRequest.getReceiverAddress());
        }
        IPage<UserOrder> userOrderPage = new Page<>(reviewedRequest.getPageNum(), reviewedRequest.getPageSize());
        userOrderPage = userOrderMapper.selectPage(userOrderPage, userOrderQueryWrapper);
        //获取全部发货仓
        ResponseResult<List<JmWarehouseResponse>> iJmWarehouseServiceAll = iJmWarehouseService.findAll();
        List<JmWarehouseResponse> jmWarehouseResponses = iJmWarehouseServiceAll.getData();
        for (UserOrder userOrder : userOrderPage.getRecords()) {
            ToBeReviewedResponse toBeReviewedResponse = new ToBeReviewedResponse();
            List<GoodsDetailsResponse> goodsDetailsResponses = new ArrayList<>();
            for (OrderGoods record : orderGoods) {
                if (userOrder.getId().equals(record.getOrderId())) {
                    GoodsDetailsResponse goodsDetailsResponse = new GoodsDetailsResponse();
                    goodsDetailsResponse.setGoodsName(record.getGoodsName());
                    goodsDetailsResponse.setShouldWarehouse(record.getShouldWarehouse());
                    goodsDetailsResponse.setNum(record.getGoodsAmount());
                    jmWarehouseResponses.forEach(
                            jmWarehouseResponse -> {
                                if (record.getShouldWarehouse().equals(jmWarehouseResponse.getWarehouseId().intValue())) {
                                    goodsDetailsResponse.setShouldWarehouseName(jmWarehouseResponse.getWarehouseName());
                                }
                                if (record.getRealWarehouse().equals(jmWarehouseResponse.getWarehouseId().intValue())) {
                                    goodsDetailsResponse.setRealWarehouseName(jmWarehouseResponse.getWarehouseName());
                                }
                            }
                    );
                    goodsDetailsResponse.setRealWarehouse(record.getRealWarehouse());
                    BeanUtils.copyProperties(record, goodsDetailsResponse);
                    goodsDetailsResponses.add(goodsDetailsResponse);
                }
                toBeReviewedResponse.setGoodsDetailsResponse(goodsDetailsResponses);
                toBeReviewedResponse.setOrderNo(userOrder.getOrderNo());
            }
            UserDetailsResponse userDetailsResponse = new UserDetailsResponse();
            userDetailsResponse.setNickName(userOrder.getReceiverName());
            userDetailsResponse.setPhone(userOrder.getReceiverPhone());
            userDetailsResponse.setAddress(userOrder.getReceiverAddress());
            toBeReviewedResponse.setUser(userDetailsResponse);
            reviewedResponses.add(toBeReviewedResponse);
        }

        toBeReviewedResponseTableDataInfo.setRows(reviewedResponses);
        toBeReviewedResponseTableDataInfo.setTotal(userOrderPage.getTotal());
        return toBeReviewedResponseTableDataInfo;
    }

    public TableDataInfo<OrderGoodsListResponse> getOrderGoodsList(OrderNoRequest request) {
        TableDataInfo<OrderGoodsListResponse> tableDataInfo = new TableDataInfo<>();
        List<OrderGoodsListResponse> orderGoodsListResponses = new ArrayList<>();
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        userOrderQueryWrapper.eq("order_no", request.getOrderNo());
        UserOrder userOrders = userOrderMapper.selectOne(userOrderQueryWrapper);
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("order_id", userOrders.getId());
        orderGoodsQueryWrapper.eq("verify_status", 1);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        List<OrderWarehouseInfoDTO> orderWarehouseInfoDTOS = new ArrayList<>();
        orderGoods.forEach(
                goods -> {
                    OrderWarehouseInfoDTO orderWarehouseInfoDTO = new OrderWarehouseInfoDTO();
                    orderWarehouseInfoDTO.setSkuId(goods.getGoodsId().longValue());
                    orderWarehouseInfoDTOS.add(orderWarehouseInfoDTO);
                }
        );
        List<OrderWarehouseInfoDTO> orderWarehouseInfoDTOList = iInventoryService.wareHouseInfo4Order(orderWarehouseInfoDTOS);
//        获取全部发货仓
        ResponseResult<List<JmWarehouseResponse>> iJmWarehouseServiceAll = iJmWarehouseService.findAll();
        List<JmWarehouseResponse> jmWarehouseResponses = iJmWarehouseServiceAll.getData();
        for (OrderGoods orderGood : orderGoods) {
            List<WarehouseResponse> warehouseResponses = new ArrayList<>();
            OrderGoodsListResponse orderGoodsListResponse = new OrderGoodsListResponse();
            BeanUtils.copyProperties(orderGood, orderGoodsListResponse);
            orderGoodsListResponse.setShouldWarehouse(orderGood.getShouldWarehouse());
            jmWarehouseResponses.forEach(
                    jmWarehouseResponse -> {
                        if (orderGood.getShouldWarehouse().equals(jmWarehouseResponse.getWarehouseId().intValue())) {
                            orderGoodsListResponse.setShouldWarehouseName(jmWarehouseResponse.getWarehouseName());
                        }
                    }
            );

            orderGoodsListResponse.setRealWarehouse(orderGood.getRealWarehouse().longValue());
            orderGoodsListResponses.add(orderGoodsListResponse);
            orderWarehouseInfoDTOList.forEach(
                    orderWarehouseInfoDTO -> {
                        if (orderWarehouseInfoDTO.getSkuId().equals(orderGood.getGoodsId().longValue())) {
                            WarehouseResponse warehouseResponse = new WarehouseResponse();
                            warehouseResponse.setSkuId(orderGood.getId());
                            warehouseResponse.setRealWarehouse(orderWarehouseInfoDTO.getWarehouseId());
                            warehouseResponse.setRealWarehouseString(orderWarehouseInfoDTO.getWarehouseName());
                            warehouseResponse.setSaleStockQuantity(orderWarehouseInfoDTO.getSaleStockQuantity());
                            warehouseResponses.add(warehouseResponse);
                        }
                    }
            );
            orderGoodsListResponse.setWarehouseResponseList(warehouseResponses);
        }
        tableDataInfo.setRows(orderGoodsListResponses);
        return tableDataInfo;
    }

    @Transactional
    public ResponseResult<Boolean> updateDaysReceipt(DaysReceiptRequest request, Long uid, String name) {
        ResponseResult<Boolean> responseResult = new ResponseResult<>();
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        if (request.getType() != null && request.getType().equals(SupplierTypeEnum.SUPPLIER.getCode())) {
            orderGoodsQueryWrapper.eq("supplier_id", request.getSupplierId());
        } else if (request.getType() != null && request.getType().equals(SupplierTypeEnum.DELIVERY_WAREHOUSE.getCode())) {
            orderGoodsQueryWrapper.eq("real_warehouse", request.getSupplierId());
        }
        if (request.getGoodsName() != null) {
            orderGoodsQueryWrapper.like("goods_name", request.getGoodsName());
        }

        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        List<Integer> goodsId = orderGoods.stream().map(OrderGoods::getOrderId).collect(Collectors.toList());
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        userOrderQueryWrapper.and(
                queryWrappe -> queryWrappe.eq("order_status", OrderStatusEnum.READY_TO_RECEIVE.getCode())
        );
        if (request.getPhoneType() == PhoneTypeEnum.BUYER.getCode()) {
            //根据手机号获取uid 加进去
        } else if (request.getPhoneType() == PhoneTypeEnum.SELLER.getCode()) {
            userOrderQueryWrapper.eq("receiver_phone", request.getPhone());
        }
        if (request.getStartTime() != null && request.getEndTime() != null) {
            userOrderQueryWrapper.between("create_time", request.getStartTime(), request.getEndTime());
        }
        if (request.getIds() != null && !request.getIds().isEmpty()) {
            userOrderQueryWrapper.in("id", request.getIds().split(","));
        }
        List<UserOrder> userOrders = userOrderMapper.selectList(userOrderQueryWrapper);
        log.info("数据是" + JSON.toJSONString(userOrders));
        log.info("数据长度是" + userOrders.size());
        List<Integer> userId = userOrders.stream().map(UserOrder::getId).collect(Collectors.toList());
        List<Integer> orderId = userId.stream().filter(goodsId::contains).collect(Collectors.toList());
        if (orderId.size() == 0) {
            log.info("查不到订单");
            responseResult.setData(false);
            return responseResult;
        }
        userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.in("id", orderId);
        userOrders = userOrderMapper.selectList(userOrderQueryWrapper);
        int row = 0;
        for (UserOrder userOrder : userOrders) {
//            Calendar c = Calendar.getInstance();
//            c.setTime(userOrder.getConfirmTime());
//            c.add(Calendar.DATE, request.getTime());
            Date confirmTime = userOrder.getConfirmTime();
            userOrder.setConfirmTime(DateUtil.getDateAfterDay(userOrder.getConfirmTime(), request.getTime()));
            row = userOrderMapper.updateById(userOrder);
            //延长收货添加日志
            if (row != 0) {
                OrderLogRequest orderLogRequest = new OrderLogRequest();
                orderLogRequest.setOperatorId(uid);
                orderLogRequest.setOperatorName(name);
                orderLogRequest.setOrderSn(userOrder.getOrderNo());
                orderLogRequest.setUserFlag((byte) 2);
                orderLogRequest.setLog("延长收货：" + request.getTime() + "天，原收货日期："
                        + DateUtil.format(confirmTime, "yyyy-MM-dd HH:mm:ss") + "，新收货日期："
                        + DateUtil.format(userOrder.getConfirmTime(), "yyyy-MM-dd HH:mm:ss"));
                orderDubboService.addOrderLog(orderLogRequest);
            }
        }
        responseResult.setData(row != 0);
        return responseResult;
    }

    @Resource
    RelocateService relocateService;

    public TableDataInfo<PreSaleToActualResponse> getPreSaleToActual(PreSaleToActualRequest request) {
        TableDataInfo<PreSaleToActualResponse> toActualResponseTableDataInfo = new TableDataInfo<>();
        List<PreSaleToActualResponse> preSaleToActualResponses = new ArrayList<>();
        QueryWrapper<UserOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_type", OrderTypeEnum.PRE_SALE_CREATE.getCode());
        queryWrapper.eq("order_status", OrderStatusEnum.READY_TO_SHIP.getCode());
        queryWrapper.eq("del_flag", DelFlag.NORMAL);
        if (request.getCreateTime() != null && request.getEndTime() != null) {
            queryWrapper.between("create_time", request.getCreateTime(), request.getEndTime());
        }
        IPage<UserOrder> userOrderPage = new Page<>(request.getPageNum(), request.getPageSize());
        queryWrapper.orderByDesc("create_time");
        userOrderPage = userOrderMapper.selectPage(userOrderPage, queryWrapper);
        List<Integer> orderId = userOrderPage.getRecords().stream().map(UserOrder::getId).collect(Collectors.toList());
        if (orderId.isEmpty()) {
            return toActualResponseTableDataInfo;
        }
        List<Long> userIds = userOrderPage.getRecords().stream().map(UserOrder::getBuyerId).collect(Collectors.toList());
        List<Integer> uIds = JSONArray.parseArray(userIds.toString(), Integer.class);
        ResponseResult<List<JmUserReponse>> jmResponse = iMemberService.getMemberByUids(uIds);
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        orderGoodsQueryWrapper.in("order_id", orderId);
        orderGoodsQueryWrapper.groupBy("goods_id");
        if (request.getGoodsName() != null) {
            orderGoodsQueryWrapper.like("goods_name", request.getGoodsName());
        }
        orderGoodsQueryWrapper.orderByDesc("create_time");
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        if (orderGoods.isEmpty()) {
            return toActualResponseTableDataInfo;
        }
        List<Long> spuIds = orderGoods.stream().map(o -> o.getSpuId().longValue()).collect(Collectors.toList());
        Map<Integer, GoodsInfoDTO> spuMap = relocateService.getGoodsSpuInfo(spuIds);
        //查询出订单数量
        for (OrderGoods orderGood : orderGoods) {
            PreSaleToActualResponse preSaleToActualResponse = new PreSaleToActualResponse();
            for (UserOrder record : userOrderPage.getRecords()) {
                if (orderGood.getOrderId().equals(record.getId())) {
                    preSaleToActualResponse.setOrderNo(record.getOrderNo());
                    jmResponse.getData().forEach(
                            jmUserReponse -> {
                                if (record.getBuyerId().intValue() == jmUserReponse.getId()) {
                                    preSaleToActualResponse.setUserName(jmUserReponse.getName());
                                }
                            }
                    );
                }
            }
            preSaleToActualResponse.setSpuId(orderGood.getSpuId());
            if (spuMap.containsKey(orderGood.getSpuId())) {
                preSaleToActualResponse.setBrand(spuMap.get(orderGood.getSpuId()).getBrandName());
                preSaleToActualResponse.setSort(spuMap.get(orderGood.getSpuId()).getCategoryName());
                preSaleToActualResponse.setGoodsImg(spuMap.get(orderGood.getSpuId()).getGoodsImage());
                preSaleToActualResponse.setGoodsName(spuMap.get(orderGood.getSpuId()).getGoodsName());
            }
            Integer orderNum = getOrderNum(orderGood.getGoodsId());
            Integer goodsNum = getGoodsNum(orderGood.getGoodsId());
            preSaleToActualResponse.setUpdateTime(DateUtil.getTime(orderGood.getUpdateTime()));
            preSaleToActualResponse.setGoodsNum(goodsNum);
            preSaleToActualResponse.setOrderNum(orderNum);
            preSaleToActualResponses.add(preSaleToActualResponse);
        }
        toActualResponseTableDataInfo.setRows(preSaleToActualResponses);
        toActualResponseTableDataInfo.setTotal(userOrderPage.getTotal());
        return toActualResponseTableDataInfo;
    }

    public Integer getOrderNum(Integer goodsId) {
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("goods_id", goodsId);
        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        List<Integer> orderId = orderGoods.stream().map(OrderGoods::getOrderId).collect(Collectors.toList());
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.eq("order_type", OrderTypeEnum.PRE_SALE_CREATE.getCode());
        userOrderQueryWrapper.ne("order_status", OrderStatusEnum.CANCEL.getCode());
        userOrderQueryWrapper.in("id", orderId);
        List<UserOrder> userOrders = userOrderMapper.selectList(userOrderQueryWrapper);
        return userOrders.size();
    }

    public Integer getGoodsNum(Integer goodsId) {
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("goods_id", goodsId);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        List<Integer> orderId = orderGoods.stream().map(OrderGoods::getOrderId).collect(Collectors.toList());
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.eq("order_type", OrderTypeEnum.PRE_SALE_CREATE.getCode());
        userOrderQueryWrapper.ne("order_status", OrderStatusEnum.CANCEL.getCode());
        userOrderQueryWrapper.in("id", orderId);
        List<UserOrder> userOrders = userOrderMapper.selectList(userOrderQueryWrapper);
        List<Integer> orderIds = userOrders.stream().map(UserOrder::getId).collect(Collectors.toList());
        orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("goods_id", goodsId);
        orderGoodsQueryWrapper.in("order_id", orderIds);
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        return orderGoodsList.stream().mapToInt(OrderGoods::getGoodsAmount).sum();
    }

    public ResponseResult<List<ReturnGoodsResponse>> getReturnGoods(Integer orderId) {
        ResponseResult<List<ReturnGoodsResponse>> returnGoodsResponseResponseResult = new ResponseResult<>();
        List<ReturnGoodsResponse> returnGoodsResponses = new ArrayList<>();
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("order_id", orderId);
        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        orderGoods.forEach(
                o -> {
                    ReturnGoodsResponse returnGoodsResponse = new ReturnGoodsResponse();
                    BeanUtils.copyProperties(o, returnGoodsResponse);
                    returnGoodsResponses.add(returnGoodsResponse);
                }
        );
        returnGoodsResponseResponseResult.setData(returnGoodsResponses);
        return returnGoodsResponseResponseResult;
    }

    public ResponseResult<InvoiceGoodsResponse> getInvoiceGoodsResponse(String orderNo) {
        ResponseResult<InvoiceGoodsResponse> invoiceGoodsResponseResponseResult = new ResponseResult<>();
        InvoiceGoodsResponse invoiceGoodsResponse = new InvoiceGoodsResponse();
        List<InvoiceGoodsListResponse> invoiceGoodsListResponseList = new ArrayList<>();
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.eq("order_no", orderNo);
        UserOrder userOrder = userOrderMapper.selectOne(userOrderQueryWrapper);
        QueryWrapper<OrderGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrderGoods::getOrderId, userOrder.getId());
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(queryWrapper);
        int num = 0;
        BigDecimal price = BigDecimal.ZERO;
        BigDecimal postage = BigDecimal.ZERO;
        for (OrderGoods orderGood : orderGoods) {
            BigDecimal realGoodsPrice = orderGood.getGoodsPrice().multiply(new BigDecimal(orderGood.getGoodsAmount()));
            int realGoodsNum = orderGood.getGoodsAmount();
            if (!orderGood.getGoodsPrice().equals(BigDecimal.ZERO) && null != orderGood.getGoodsPrice()) {
                if (orderGood.getAfterSealStatus().equals(AfterSaleStatusEnum.REFUND.getCode().byteValue()) || orderGood.getAfterSealStatus().equals(AfterSaleStatusEnum.REFUND_GOODS_AGREE.getCode().byteValue())) {
                    if (!orderGood.getReturnPrice().equals(BigDecimal.ZERO) && null != orderGood.getReturnPrice()) {
                        price = price.add(orderGood.getGoodsPrice().multiply(new BigDecimal(orderGood.getGoodsAmount()))).subtract(orderGood.getReturnPrice());
                        realGoodsNum = realGoodsNum - orderGood.getReturnCount();
                    } else {
                        price = price.add(orderGood.getGoodsPrice().multiply(new BigDecimal(orderGood.getGoodsAmount())));
                    }
                    if (!orderGood.getGoodsFreightFee().equals(BigDecimal.ZERO) && null != orderGood.getGoodsFreightFee()) {
                        if (!orderGood.getReturnPostage().equals(BigDecimal.ZERO) && null != orderGood.getReturnPostage()) {
                            postage = postage.add(orderGood.getGoodsFreightFee()).subtract(orderGood.getReturnPostage());
                        } else {
                            postage = postage.add(orderGood.getGoodsFreightFee());
                        }
                    }
                    if (!orderGood.getReturnPrice().equals(BigDecimal.ZERO) && null != orderGood.getReturnPrice()) {
                        realGoodsPrice = realGoodsPrice.subtract(orderGood.getReturnPrice());
                    }
                }
            }
            num += realGoodsNum;
            //最后一个元素是邮费
            InvoiceGoodsListResponse invoiceGoodsListResponse = new InvoiceGoodsListResponse();
            BeanUtils.copyProperties(orderGood, invoiceGoodsListResponse);
            invoiceGoodsListResponse.setGoodsAmount(realGoodsNum);
            invoiceGoodsListResponse.setGoodsPrice(realGoodsPrice);
            invoiceGoodsListResponseList.add(invoiceGoodsListResponse);
        }
        //总金额 = 总商品金额 + 总邮费金额
        BigDecimal totalPrice = price.add(postage);
        invoiceGoodsResponse.setInvoiceGoodsListResponseList(invoiceGoodsListResponseList);
        invoiceGoodsResponse.setNum(num);
        invoiceGoodsResponse.setPrice(totalPrice);
        invoiceGoodsResponseResponseResult.setData(invoiceGoodsResponse);
        return invoiceGoodsResponseResponseResult;
    }

    public ResponseResult<Boolean> approvedExamineRequest(ApprovedExamineRequest request) {
        ResponseResult<Boolean> responseResult = new ResponseResult<>();
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.in("order_no", request.getOrderNo());
        List<UserOrder> userOrders = userOrderMapper.selectList(userOrderQueryWrapper);
        List<Integer> orderId = userOrders.stream().map(UserOrder::getId).collect(Collectors.toList());
        QueryWrapper<OrderGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("order_id", orderId);
        OrderGoods orderGoods = new OrderGoods();
        orderGoods.setVerifyStatus((byte) 0);
        int row = orderGoodsMapper.update(orderGoods, queryWrapper);
        //自动拆单
        for (UserOrder userOrder : userOrders) {
            AutoSpiltRequest autoSpiltRequest = new AutoSpiltRequest();
            autoSpiltRequest.setOrderNo(userOrder.getOrderNo());
            autoSpiltService.autoSpiltOrder(autoSpiltRequest);
        }
        responseResult.setData(row != 0);
        return responseResult;
    }

    public ResponseResult<Boolean> approvedExamineAll() {
        ResponseResult<Boolean> responseResult = new ResponseResult<>();
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        orderGoodsQueryWrapper.eq("verify_status", 1);
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        OrderGoods orderGoods = new OrderGoods();
        orderGoods.setVerifyStatus((byte) 0);
        int row = orderGoodsMapper.update(orderGoods, orderGoodsQueryWrapper);
        //自动拆单
        for (OrderGoods g : orderGoodsList) {
            AutoSpiltRequest autoSpiltRequest = new AutoSpiltRequest();
            autoSpiltRequest.setOrderId(g.getOrderId());
            autoSpiltService.autoSpiltOrder(autoSpiltRequest);
        }
        responseResult.setData(row != 0);
        return responseResult;
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<Boolean> updateOrderDetails(UpdateOrderDetailsRequest request, Long uid, String name) {
        ResponseResult<Boolean> responseResult = new ResponseResult<>();
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.eq("id", request.getOrderId());
        UserOrder userOrder = userOrderMapper.selectOne(userOrderQueryWrapper);
        if (!(userOrder.getOrderStatus().equals(OrderStatusEnum.READY_TO_SHIP.getCode()) ||
                userOrder.getOrderStatus().equals(OrderStatusEnum.READY_TO_PAY.getCode()))) {
            throw new BaseException(500, "该订单不是待发货或者待付款状态，不能修改收件信息");
        }
        String oldValue = "";
        String newValue = "";
        if(!request.getReceiverName().equals(userOrder.getReceiverName())){
            oldValue+=userOrder.getReceiverName();
            newValue+=request.getReceiverName();
        }
        if(!request.getReceiverPhone().equals(userOrder.getReceiverPhone())){
            oldValue+=" ".concat(userOrder.getReceiverPhone());
            newValue+=" ".concat(request.getReceiverPhone());
        }
        if(!request.getReceiverAddress().equals(userOrder.getReceiverAddress())){
            oldValue+=" ".concat(userOrder.getReceiverAddress());
            newValue+=" ".concat(request.getReceiverAddress());
        }
        if(!request.getRemark().equals(userOrder.getRemark())){
            oldValue+=" 订单备注：".concat(userOrder.getRemark());
            newValue+=" 订单备注：".concat(request.getRemark());
        }
        userOrder.setRemark(request.getRemark());
        userOrder.setReceiverName(request.getReceiverName());
        userOrder.setReceiverPhone(request.getReceiverPhone());
        userOrder.setReceiverAddress(request.getReceiverAddress());
        int row = userOrderMapper.updateById(userOrder);
        //添加日志
        if (row != 0) {
            OrderLogRequest orderLogRequest = new OrderLogRequest();
            orderLogRequest.setOperatorId(uid);
            orderLogRequest.setOperatorName(name);
            orderLogRequest.setOrderSn(userOrder.getOrderNo());
            orderLogRequest.setLog("修改收货信息-原值：" + oldValue+ " 改为：" + newValue);
            orderLogRequest.setUserFlag((byte) 2);
            orderDubboService.addOrderLog(orderLogRequest);
        }
        responseResult.setData(row != 0);
        if (userOrder.getOrderStatus().equals(OrderStatusEnum.READY_TO_PAY.getCode()) || userOrder.getOrderType().equals(OrderTypeEnum.PRE_SALE_CREATE.getCode())) {
            return responseResult;
        }
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("order_id",userOrder.getId());
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        Set<Byte> verifyStatus = orderGoods.stream().map(OrderGoods::getVerifyStatus).collect(Collectors.toSet());
        if(verifyStatus.contains((byte)1)){
            responseResult.setData(true);
            return responseResult;
        }
        //查询出订单下包裹商品
        QueryWrapper<LogisticsGoods> queryLogisticsGoods = new QueryWrapper<>();
        queryLogisticsGoods.eq("logistics_status", LogisticsStatusEnum.WAIT_SEND.getCode()).eq("del_flag", 0)
                .eq("order_no", userOrder.getOrderNo());
        List<LogisticsGoods> logisticsGoodsList = logisticsGoodsMapper.selectList(queryLogisticsGoods);
        if (logisticsGoodsList.isEmpty()) {
            throw new BaseException(500, "该订单下未查询到包裹商品信息");
        }
        Set<String> logisticsNos = logisticsGoodsList.stream().map(LogisticsGoods::getLogisticsNo).collect(Collectors.toSet());
        //查询出这些商品所在包裹的详细信息
        QueryWrapper<OrderLogistics> queryOrderLogistics = new QueryWrapper<>();
        queryOrderLogistics.in("logistics_no", logisticsNos);
        List<OrderLogistics> orderLogisticsList = orderLogisticsMapper.selectList(queryOrderLogistics);
        if (orderLogisticsList.isEmpty()) {
            throw new BaseException(500, "该订单下未查询到包裹信息");
        }
        Map<String, OrderLogistics> orderLogisticsMap = new HashMap<>(orderLogisticsList.size());
        for (OrderLogistics orderLogistics : orderLogisticsList) {
            orderLogisticsMap.put(orderLogistics.getLogisticsNo(), orderLogistics);
        }
        //判断包裹中是否还有其他订单商品
        for (String logisticsNo : logisticsNos) {
            LogisticsGoods updateLogisticsGoods = new LogisticsGoods();
            updateLogisticsGoods.setReceiverAddress(request.getReceiverAddress());
            updateLogisticsGoods.setReceiverPhone(request.getReceiverPhone());
            updateLogisticsGoods.setReceiverName(request.getReceiverName());
            OrderLogistics orderLogistics = new OrderLogistics();
            orderLogistics.setReceiverName(request.getReceiverName());
            orderLogistics.setReceiverPhone(request.getReceiverPhone());
            orderLogistics.setReceiverAddress(request.getReceiverAddress());
            orderLogistics.setReceiverInfo(request.getReceiverPhone() + request.getReceiverAddress());
            if (isHaveOtherOrder(logisticsNo)) {
                List<Integer> ids = logisticsGoodsList.stream().filter(g -> g.getLogisticsNo().equals(logisticsNo))
                        .map(LogisticsGoods::getId).collect(Collectors.toList());
                //有其他订单商品 生成新包裹并将商品添加至新包裹
                BeanUtils.copyProperties(orderLogisticsMap.get(logisticsNo), orderLogistics);
                orderLogistics.setReceiverName(request.getReceiverName());
                orderLogistics.setReceiverPhone(request.getReceiverPhone());
                orderLogistics.setReceiverAddress(request.getReceiverAddress());
                orderLogistics.setReceiverInfo(request.getReceiverPhone() + request.getReceiverAddress());
                orderLogistics.setLogisticsNo(autoSpiltService.getRandomString());
                orderLogistics.setSpiltMergeStatus(SpiltMergeStatusEnum.SPILT.getCode());
                orderLogisticsMapper.insert(orderLogistics);
                UpdateWrapper<LogisticsGoods> updateWrapper = new UpdateWrapper<>();
                if(!ids.isEmpty()){
                    updateWrapper.in("id", ids);
                }
                updateLogisticsGoods.setLogisticsNo(orderLogistics.getLogisticsNo());
                logisticsGoodsMapper.update(updateLogisticsGoods, updateWrapper);
            } else {
                //无其他商品只修改包裹商品收货信息
                logisticsGoodsMapper.update(updateLogisticsGoods, queryLogisticsGoods);
                UpdateWrapper<OrderLogistics> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("logistics_no", logisticsNo);
                orderLogisticsMapper.update(orderLogistics, updateWrapper);
            }
        }
        return responseResult;
    }

    /**
     * 判断有无其他订单
     *
     * @param logisticsNo
     * @return
     */
    public boolean isHaveOtherOrder(String logisticsNo) {
        QueryWrapper<LogisticsGoods> queryWrapper = new QueryWrapper();
        queryWrapper.eq("logistics_no", logisticsNo).eq("del_flag", 0);
        List<LogisticsGoods> list = logisticsGoodsMapper.selectList(queryWrapper);
        Set<String> orderNos = list.stream().map(LogisticsGoods::getOrderNo).collect(Collectors.toSet());
        return orderNos.size() > 1;
    }

    public TableDataInfo<PartialResponse> getPartialNew(PartialRequest request) {
        TableDataInfo<PartialResponse> partialResponseTableDataInfo = new TableDataInfo<>();
        List<PartialResponse> partialResponses = new ArrayList<>();
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        if (request.getType() != null && request.getType().equals(SupplierTypeEnum.SUPPLIER.getCode())) {
            orderGoodsQueryWrapper.eq("supplier_id", request.getSupplierId());
        } else if (request.getType() != null && request.getType().equals(SupplierTypeEnum.DELIVERY_WAREHOUSE.getCode())) {
            orderGoodsQueryWrapper.eq("real_warehouse", request.getSupplierId());
        }
        if (request.getGoodsName() != null) {
            orderGoodsQueryWrapper.like("goods_name", request.getGoodsName());
        }
        if (request.getStartTime() != null && request.getEndTime() != null) {
            orderGoodsQueryWrapper.between("create_time", request.getStartTime(), request.getEndTime());
        }
        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        orderGoodsQueryWrapper.eq("goods_status", LogisticsStatusEnum.PART_SEND.getCode()).or().eq("goods_status", LogisticsStatusEnum.WAIT_SEND.getCode());
        IPage<OrderGoods> orderGoodsPage = new Page<>(request.getPageNum(), request.getPageSize());
        orderGoodsPage = orderGoodsMapper.selectPage(orderGoodsPage, orderGoodsQueryWrapper);
        List<Integer> goodsIds = orderGoodsPage.getRecords().stream()
                .map(OrderGoods::getOrderId)
                .collect(Collectors.toList());
        //剔除方法
        QueryWrapper<OrderGoods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.in("order_id", goodsIds);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(goodsQueryWrapper);
        List<Integer> orderIds = orderGoods.stream()
                .filter(o -> o.getGoodsStatus().equals(LogisticsStatusEnum.PART_SEND.getCode()) || o.getGoodsStatus().equals(LogisticsStatusEnum.WAIT_RECEIVE.getCode()))
                .map(OrderGoods::getOrderId).collect(Collectors.toList());
        if (orderIds.size() == 0) {
            return partialResponseTableDataInfo;
        }
//        //获取全部供应商
//        List<JmSupplierResponse> jmSupplierResponses = getSupply();
//        //获取全部发货仓
//        ResponseResult<List<JmWarehouseResponse>> iJmWarehouseServiceAll = iJmWarehouseService.findAll();
//        List<JmWarehouseResponse> jmWarehouseResponses = iJmWarehouseServiceAll.getData();
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.in("id", orderIds);
        userOrderQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        if (request.getOrderNo() != null) {
            userOrderQueryWrapper.eq("order_no", request.getOrderNo());
        }
        if (request.getStartTime() != null && request.getEndTime() != null) {
            userOrderQueryWrapper.between("create_time", request.getStartTime(), request.getEndTime());
        }
        userOrderQueryWrapper.orderBy(true, false, "create_time");
        List<UserOrder> orders = userOrderMapper.selectList(userOrderQueryWrapper);
        orders.forEach(
                userOrder -> {
                    UserDetailsResponse userDetailsResponse = new UserDetailsResponse();
                    PartialResponse partialResponse = new PartialResponse();
                    BeanUtils.copyProperties(userOrder, partialResponse);
                    partialResponse.setCreateTime(DateUtil.getTime(userOrder.getCreateTime()));
                    if (userOrder.getPayTime() != null) {
                        partialResponse.setPayTime(DateUtil.getTime(userOrder.getPayTime()));
                    }
                    PayChannelEnum payChannelEnum = EnumUtil.getByCode(userOrder.getPayType(), PayChannelEnum.class);
                    partialResponse.setPayType(payChannelEnum.getDescription());
                    OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(userOrder.getOrderStatus(), OrderStatusEnum.class);
                    partialResponse.setOrderStatusString(orderStatusEnum.getMessage());
                    userDetailsResponse.setAddress(userOrder.getReceiverAddress());
                    userDetailsResponse.setPhone(userOrder.getReceiverPhone());
                    userDetailsResponse.setNickName(userOrder.getReceiverName());
                    partialResponse.setUser(userDetailsResponse);
                    partialResponses.add(partialResponse);
                }
        );
        orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.in("order_id", orderIds);
        orderGoodsQueryWrapper.eq("goods_status", LogisticsStatusEnum.PART_SEND.getCode()).or().eq("goods_status", LogisticsStatusEnum.WAIT_SEND.getCode());
        List<OrderGoods> goods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        for (PartialResponse partialResponse : partialResponses) {
            List<PartialOneResponse> partialOneResponses = new ArrayList<>();
            for (OrderGoods orderGood : goods) {
                if (partialResponse.getId().equals(orderGood.getOrderId())) {
                    PartialOneResponse partialOneResponse = new PartialOneResponse();
                    AfterSaleStatusEnum afterSaleStatusEnum = EnumUtil.getByCode(orderGood.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
                    partialOneResponse.setAfterSealStatusString(afterSaleStatusEnum.getMsg());
                    BeanUtils.copyProperties(orderGood, partialOneResponse);
                    if (orderGood.getSelfFlag() == SelfFlagEnum.YES_SELF.getCode()) {
//                        if (orderGood.getRealWarehouse() != null) {
//                            partialOneResponse.setSupplierId(orderGood.getRealWarehouse());
//                            for (JmWarehouseResponse jmWarehouseRespons : jmWarehouseResponses) {
//                                partialOneResponse.setSupplierName("实际发货仓");
//                                if (orderGood.getSupplierId().equals(jmWarehouseRespons.getWarehouseId().intValue())) {
//                                    partialOneResponse.setSupplierName(jmWarehouseRespons.getWarehouseName());
//                                }
//                            }
//
//                        } else if (orderGood.getSelfFlag() == SelfFlagEnum.NO_SELF.getCode()) {
//                            partialOneResponse.setSupplierId(orderGood.getShouldWarehouse());
//
//                            for (JmSupplierResponse jmSupplierResponse : jmSupplierResponses) {
//                                if (orderGood.getSupplierId().equals(jmSupplierResponse.getSupplierId().intValue())) {
//                                    partialOneResponse.setSupplierName(jmSupplierResponse.getSupplierCompanyName());
//                                }
//                            }
//                        }
                    }
                    partialOneResponses.add(partialOneResponse);
                }
            }
            partialResponse.setPartialOneResponses(partialOneResponses);
        }
        partialResponseTableDataInfo.setRows(partialResponses);
        partialResponseTableDataInfo.setTotal(orderGoodsPage.getTotal());
        return partialResponseTableDataInfo;
    }

    @Transactional
    public ResponseResult<Boolean> confirmedAudit(ConfirmedAuditRequest request) throws Exception {
        ResponseResult<Boolean> responseResult = new ResponseResult<>();
        Integer orderId = 0;
        for (ConfirmedAuditOneRequest confirmedAuditOneRequest : request.getConfirmedAuditOneRequests()) {
            List<TransferWarehouseDTO> transferWarehouses = new ArrayList<>();
            orderId = confirmedAuditOneRequest.getOrderId();
            QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
            orderGoodsQueryWrapper.lambda().eq(OrderGoods::getOrderId, confirmedAuditOneRequest.getOrderId())
                    .eq(OrderGoods::getGoodsId, confirmedAuditOneRequest.getGoodsId());
            OrderGoods orderGoods = orderGoodsMapper.selectOne(orderGoodsQueryWrapper);
            if (!orderGoods.getRealWarehouse().equals(confirmedAuditOneRequest.getWarehouseId())) {
                SupplyStockDeductDTO supplyStockDeductDTO = new SupplyStockDeductDTO();
                supplyStockDeductDTO.setSkuId(confirmedAuditOneRequest.getGoodsId().longValue());
                supplyStockDeductDTO.setStockNum(confirmedAuditOneRequest.getGoodsAmount());
                supplyStockDeductDTO.setWareId(confirmedAuditOneRequest.getWarehouseId().longValue());
                Boolean result = iOrderInventoryService.deductStockBySkuId(supplyStockDeductDTO);
                if (!result) {
                    throw new Exception("仓库库存不足");
                }
                //调用库存 添加 减少的接口
                TransferWarehouseDTO transferWarehouseDTO = new TransferWarehouseDTO();
                transferWarehouseDTO.setGoodsSkuId(confirmedAuditOneRequest.getGoodsId().longValue());
                transferWarehouseDTO.setNewWarehouseId(confirmedAuditOneRequest.getWarehouseId().longValue());
                transferWarehouseDTO.setOldWarehouseId(orderGoods.getRealWarehouse().longValue());
                transferWarehouseDTO.setSaleStockQuantity(confirmedAuditOneRequest.getGoodsAmount());
                transferWarehouses.add(transferWarehouseDTO);
                if (!iOrderInventoryService.transferWarehouseEvent(transferWarehouses)) {
                    throw new Exception("调仓失败");
                }
            }
            orderGoodsQueryWrapper = new QueryWrapper<>();
            orderGoodsQueryWrapper.eq("order_id", confirmedAuditOneRequest.getOrderId());
            orderGoodsQueryWrapper.eq("goods_id", confirmedAuditOneRequest.getGoodsId());
            OrderGoods orderGoodsEntity = orderGoodsMapper.selectOne(orderGoodsQueryWrapper);
            orderGoodsEntity.setVerifyStatus((byte) 0);
            orderGoodsEntity.setShouldWarehouse(confirmedAuditOneRequest.getWarehouseId());
            orderGoodsMapper.updateById(orderGoodsEntity);
        }
        //拆单
        if (orderCheckPass(orderId)) {
            AutoSpiltRequest autoSpiltRequest = new AutoSpiltRequest();
            autoSpiltRequest.setOrderId(orderId);
            autoSpiltService.autoSpiltOrder(autoSpiltRequest);
        }
        responseResult.setData(true);
        return responseResult;
    }

    public ResponseResult<List<DistributionResponse>> serviceChargeList(String orderNo) {
        ResponseResult<List<DistributionResponse>> responseResponseResult = new ResponseResult<>();
        List<DistributionResponse> distributionResponses = new ArrayList<>();
        ResponseResult<Page> response = iFenXiaoService.getFenxiao(orderNo, null);
        log.info("推广金额是" + JSON.toJSONString(response));
        for (Object record : response.getData().getRecords()) {
            FenXiaoReponse fenXiaoReponse = (FenXiaoReponse) record;
            if (fenXiaoReponse.getType().equals(FenXiaoType.推广收益)) {
                DistributionResponse distributionResponse = new DistributionResponse();
                ResponseResult<JmUserReponse> jmUserReponseR = iMemberService.getMemberByUid(fenXiaoReponse.getUid());
                distributionResponse.setUid(fenXiaoReponse.getUid());
                JmUserReponse jmUserReponse = jmUserReponseR.getData();
                distributionResponse.setPrice(fenXiaoReponse.getYongjin());
                distributionResponse.setIsJumi(jmUserReponse.getIsJumi().name());
                distributionResponse.setBuyerLevel(jmUserReponseR.getData().getLevel().getDesc());
                distributionResponse.setNickName(jmUserReponse.getName());
                distributionResponse.setPhone(jmUserReponse.getMobile());
                distributionResponses.add(distributionResponse);
            }
        }
        responseResponseResult.setData(distributionResponses);
        return responseResponseResult;
    }

    public ResponseResult<List<DistributionResponse>> serviceAmountList(String orderNo) {
        ResponseResult<List<DistributionResponse>> responseResponseResult = new ResponseResult<>();
        List<DistributionResponse> distributionResponses = new ArrayList<>();
        ResponseResult<Page> response = iFenXiaoService.getFenxiao(orderNo, null);
        log.info("服务金额" + JSON.toJSONString(response));
        for (Object record : response.getData().getRecords()) {
            FenXiaoReponse fenXiaoReponse = (FenXiaoReponse) record;
            if (fenXiaoReponse.getType().equals(FenXiaoType.服务收益)) {
                DistributionResponse distributionResponse = new DistributionResponse();
                ResponseResult<JmUserReponse> jmUserReponseR = iMemberService.getMemberByUid(fenXiaoReponse.getUid());
                JmUserReponse jmUserReponse = jmUserReponseR.getData();
                distributionResponse.setUid(fenXiaoReponse.getUid());
                distributionResponse.setIsJumi(jmUserReponse.getIsJumi().name());
                distributionResponse.setBuyerLevel(jmUserReponseR.getData().getLevel().getDesc());
                distributionResponse.setNickName(jmUserReponse.getName());
                distributionResponse.setPhone(jmUserReponse.getMobile());
                distributionResponse.setPrice(fenXiaoReponse.getYongjin());
                distributionResponses.add(distributionResponse);
            }
        }
        responseResponseResult.setData(distributionResponses);
        return responseResponseResult;
    }

    //海外商品
    public TableDataInfo<OrderGoodsAllResponse> getImportList(OrderGoodsRequest request) {
        TableDataInfo<OrderGoodsAllResponse> orderGoodsAllResponseTableDataInfo = new TableDataInfo<>();
        List<OrderGoodsAllResponse> orderGoodsAllResponses = new ArrayList<>();
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        if (request.getType() != null && request.getType().equals(SupplierTypeEnum.SUPPLIER.getCode())) {
            orderGoodsQueryWrapper.eq("supplier_id", request.getSupplier());
        }
        if (request.getGoodsName() != null) {
            orderGoodsQueryWrapper.like("goods_name", request.getGoodsName());
        }
        orderGoodsQueryWrapper.eq("is_import", IsImportEnum.YES.getCode());
        orderGoodsQueryWrapper.eq("goods_status", LogisticsStatusEnum.WAIT_SEND.getCode());
        orderGoodsQueryWrapper.orderByDesc("id");
//        IPage<OrderGoods> orderGoodsPage = new Page<>(request.getPageNum(), request.getPageSize());
        //订单商品信息
        List<OrderGoods> goods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        List<Integer> goodsId = goods.stream().map(OrderGoods::getOrderId).collect(Collectors.toList());
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        if (request.getOrderNo() != null) {
            userOrderQueryWrapper.eq("order_no", request.getOrderNo());
        }
        if (request.getStartTime() != null && request.getEndTime() != null) {
            //下单时间
            userOrderQueryWrapper.between("create_time", request.getStartTime(), request.getEndTime());
        }
        if (request.getPayNo() != null) {
            userOrderQueryWrapper.eq("pay_no", request.getPayNo());
        }
        if (request.getPhoneType() == PhoneTypeEnum.BUYER.getCode()) {
            ResponseResult<Integer> uid = iMemberService.getUidByMobile(request.getPhone());
            if (uid != null) {
                userOrderQueryWrapper.eq("buyer_id", uid.getData());
            } else {
                return orderGoodsAllResponseTableDataInfo;
            }
        } else if (request.getPhoneType() == PhoneTypeEnum.SELLER.getCode()) {
            userOrderQueryWrapper.eq("receiver_phone", request.getPhone());
        }
        userOrderQueryWrapper.orderByDesc("id");
        List<UserOrder> orders = userOrderMapper.selectList(userOrderQueryWrapper);
        List<Integer> orderId = orders.stream().map(UserOrder::getId).collect(Collectors.toList());
        //按条件查询出订单id
        List<Integer> userOrderId = orderId.stream().filter(goodsId::contains).collect(Collectors.toList());
        if (userOrderId.size() == 0) {
            return orderGoodsAllResponseTableDataInfo;
        }
        userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.in("id", userOrderId);
        userOrderQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        userOrderQueryWrapper.orderBy(true, false, "create_time");
        IPage<UserOrder> userOrderIPage = new Page<>(request.getPageNum(), request.getPageSize());
        userOrderIPage = userOrderMapper.selectPage(userOrderIPage, userOrderQueryWrapper);
        userOrderIPage.getRecords().forEach(
                userOrder -> {
                    UserDetailsResponse userDetailsResponse = new UserDetailsResponse();
                    OrderGoodsAllResponse orderGoodsAllResponse = new OrderGoodsAllResponse();
                    BeanUtils.copyProperties(userOrder, orderGoodsAllResponse);
                    orderGoodsAllResponse.setCreateTime(DateUtil.getTime(userOrder.getCreateTime()));
                    if (userOrder.getPayTime() != null) {
                        orderGoodsAllResponse.setPayTime(DateUtil.getTime(userOrder.getPayTime()));
                    }
                    PayChannelEnum payChannelEnum = EnumUtil.getByCode(userOrder.getPayType(), PayChannelEnum.class);
                    orderGoodsAllResponse.setPayType(payChannelEnum.getDescription());
                    OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(userOrder.getOrderStatus(), OrderStatusEnum.class);
                    orderGoodsAllResponse.setOrderStatusString(orderStatusEnum.getMessage());
//                    }
                    orderGoodsAllResponse.setPayAmount(userOrder.getPayAmount());
                    userDetailsResponse.setAddress(userOrder.getReceiverAddress());
                    userDetailsResponse.setPhone(userOrder.getReceiverPhone());
                    userDetailsResponse.setNickName(userOrder.getReceiverName());
                    orderGoodsAllResponse.setUser(userDetailsResponse);
                    orderGoodsAllResponses.add(orderGoodsAllResponse);
                }
        );
        //获取全部供应商
        List<JmSupplierResponse> jmSupplierResponses = getSupply();
        //获取全部发货仓
        ResponseResult<List<JmWarehouseResponse>> iJmWarehouseServiceAll = iJmWarehouseService.findAll();
        List<JmWarehouseResponse> jmWarehouseResponses = iJmWarehouseServiceAll.getData();
        orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.in("order_id", userOrderId);
        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        for (OrderGoodsAllResponse orderGoodsAllResponse : orderGoodsAllResponses) {
            List<OrderGoodsResponse> orderGoodsResponses = new ArrayList<>();
            for (OrderGoods record : orderGoods) {
                if (orderGoodsAllResponse.getId().equals(record.getOrderId())) {
                    OrderGoodsResponse orderGoodsResponse = new OrderGoodsResponse();
                    //根据商品id 获取商品名称
                    LogisticsStatusEnum logisticsStatusEnum = EnumUtil.getByCode(record.getGoodsStatus(), LogisticsStatusEnum.class);
                    AfterSaleStatusEnum afterSaleStatusEnum = EnumUtil.getByCode(record.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
                    BeanUtils.copyProperties(record, orderGoodsResponse);
                    orderGoodsResponse.setSelfFlag(record.getSelfFlag());
                    orderGoodsResponse.setAfterSealStatus(record.getAfterSealStatus());
                    orderGoodsResponse.setSelfFlag(record.getSelfFlag());
                    if (record.getSelfFlag() == SelfFlagEnum.YES_SELF.getCode()) {
                        if (record.getRealWarehouse() != null) {
                            orderGoodsResponse.setSupplierId(record.getRealWarehouse());
                            for (JmWarehouseResponse response : jmWarehouseResponses) {
                                if (record.getRealWarehouse().equals(response.getWarehouseId().intValue())) {
                                    orderGoodsResponse.setSupplierName(response.getWarehouseName());
                                }
                            }
                        }
                    }
                    if (record.getSelfFlag() == SelfFlagEnum.NO_SELF.getCode()) {
                        orderGoodsResponse.setSupplierId(record.getShouldWarehouse());
                        if (record.getShouldWarehouse() != null) {
                            for (JmSupplierResponse jmSupplierResponse : jmSupplierResponses) {
                                if (record.getSupplierId().equals(jmSupplierResponse.getSupplierId().intValue())) {
                                    orderGoodsResponse.setSupplierName(jmSupplierResponse.getSupplierCompanyName());
                                }
                            }
                        }

                    }
                    orderGoodsResponse.setAfterSealStatusString(afterSaleStatusEnum.getMsg());
                    orderGoodsResponse.setGoodsStatusString(logisticsStatusEnum.getMsg());
                    orderGoodsResponses.add(orderGoodsResponse);
                }
            }
            orderGoodsAllResponse.setOrderGoodsResponses(orderGoodsResponses);
        }
        orderGoodsAllResponseTableDataInfo.setRows(orderGoodsAllResponses);
        orderGoodsAllResponseTableDataInfo.setTotal(userOrderIPage.getTotal());
        return orderGoodsAllResponseTableDataInfo;
    }


    /**
     * 海外商品导出
     *
     * @param request
     * @return
     */
    public ExportExcelCommonResponse<ImportNoSelfResponse> excelExport(OrderGoodsRequest request) {
        String fileName = "ImportWaitSend.xlsx";
        ExportExcelCommonResponse exportExcelCommonResponse = new ExportExcelCommonResponse();
        List<ImportNoSelfResponse> result = new ArrayList<>();
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        boolean f = false;
        if (request.getOrderNo() != null) {
            userOrderQueryWrapper.eq("order_no", request.getOrderNo());
            f = true;
        }
        if (request.getStartTime() != null && request.getEndTime() != null) {
            //下单时间
            userOrderQueryWrapper.between("create_time", request.getStartTime(), request.getEndTime());
            f = true;
        }
        if (request.getPayNo() != null) {
            userOrderQueryWrapper.eq("pay_no", request.getPayNo());
            f = true;
        }
        if (request.getPhoneType() == PhoneTypeEnum.BUYER.getCode()) {
            ResponseResult<Integer> uid = iMemberService.getUidByMobile(request.getPhone());
            if (uid.getData() != null) {
                userOrderQueryWrapper.eq("buyer_id", uid.getData());
                f = true;
            }
        } else if (request.getPhoneType() == PhoneTypeEnum.SELLER.getCode()) {
            userOrderQueryWrapper.eq("receiver_phone", request.getPhone());
            f = true;
        }
        if (request.getIds() != null && !request.getIds().trim().isEmpty()) {
            userOrderQueryWrapper.in("id", request.getIds());
        }
        List<Integer> ids = new ArrayList<>();
        Map<Integer, UserOrder> userOrderMap = new HashMap<>();
        if (f) {
            List<UserOrder> userOrderList = userOrderMapper.selectList(userOrderQueryWrapper);
            if (userOrderList.isEmpty()) {
                exportExcelCommonResponse.setFileName(fileName);
                exportExcelCommonResponse.setData(result);
                return exportExcelCommonResponse;
            }
            for (UserOrder userOrder : userOrderList) {
                userOrderMap.put(userOrder.getId(), userOrder);
            }
            ids = userOrderList.stream().map(UserOrder::getId).collect(Collectors.toList());
        }
        QueryWrapper<OrderGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0).eq("is_import", IsImportEnum.YES.getCode())
                .eq("goods_status", LogisticsStatusEnum.WAIT_SEND.getCode());
        if (request.getGoodsName() != null) {
            queryWrapper.like("goods_name", request.getGoodsName());
        }
        if (request.getSupplier() != null) {
            queryWrapper.eq("supplier_id", request.getSupplier());
        }
        if (!ids.isEmpty()) {
            queryWrapper.in("order_id", ids);
        }
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(queryWrapper);
        if (ids.isEmpty() && !f && !orderGoodsList.isEmpty()) {
            userOrderQueryWrapper.in("id", orderGoodsList.stream().map(OrderGoods::getOrderId).collect(Collectors.toList()));
            List<UserOrder> userOrderList = userOrderMapper.selectList(userOrderQueryWrapper);
            ids = userOrderList.stream().map(UserOrder::getId).collect(Collectors.toList());
            for (UserOrder userOrder : userOrderList) {
                userOrderMap.put(userOrder.getId(), userOrder);
            }
        }
        Map<Integer, String> supplyMap = supplyMap();
        for (OrderGoods orderGoods : orderGoodsList) {
            ImportNoSelfResponse exportOrderAllResponse = new ImportNoSelfResponse();
            exportOrderAllResponse.setOrderId(orderGoods.getOrderId());
            LogisticsStatusEnum logisticsStatusEnum =
                    EnumUtil.getByCode(orderGoods.getGoodsStatus(), LogisticsStatusEnum.class);
            exportOrderAllResponse.setOrderStatus(logisticsStatusEnum.getMsg());
            AfterSaleStatusEnum afterSaleStatusEnum =
                    EnumUtil.getByCode(orderGoods.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
            exportOrderAllResponse.setAfterSealStatusString(afterSaleStatusEnum.getMsg());
            if (userOrderMap.containsKey(orderGoods.getOrderId())) {
                UserOrder userOrder = userOrderMap.get(orderGoods.getOrderId());
                exportOrderAllResponse.setOrderNo(userOrder.getOrderNo());
                exportOrderAllResponse.setPhone(userOrder.getReceiverPhone());
                exportOrderAllResponse.setAddress(userOrder.getReceiverAddress());
                exportOrderAllResponse.setNickName(userOrder.getReceiverName());
                exportOrderAllResponse.setCreateTime(userOrder.getCreateTime());
                exportOrderAllResponse.setPayTime(userOrder.getPayTime());
//                exportOrderAllResponse.setCardNo(userOrder.getReceiverCardNo());
            }
            if (supplyMap.containsKey(orderGoods.getSupplierId())) {
                exportOrderAllResponse.setSupplierName(supplyMap.get(orderGoods.getSupplierId()));
            }
            exportOrderAllResponse.setGoodsAmount(orderGoods.getGoodsAmount());
            exportOrderAllResponse.setRealSendAmount(orderGoods.getGoodsAmount());
            exportOrderAllResponse.setGoodsName(orderGoods.getGoodsName());
            exportOrderAllResponse.setGoodsId(orderGoods.getGoodsId());
            result.add(exportOrderAllResponse);
        }
        if (!ids.isEmpty()) {
            DeliverGoodsRequest deliverGoodsRequest = new DeliverGoodsRequest();
            deliverGoodsRequest.setOrderIds(ids);
            orderDubboService.deliverGoods(deliverGoodsRequest);
        }
        exportExcelCommonResponse.setFileName(fileName);
        exportExcelCommonResponse.setData(result);
        return exportExcelCommonResponse;
    }


    /**
     * @return
     */
    public Map<Integer, String> supplyMap() {
        List<JmSupplierResponse> list = getSupply();
        Map<Integer, String> map = new HashMap<>(list.size());
        for (JmSupplierResponse jmSupplierResponse : list) {
            map.put(jmSupplierResponse.getSupplierId().intValue(), jmSupplierResponse.getSupplierCompanyName());
        }
        return map;
    }

    /**
     * 判断该订单下的全部商品是否全部不需要审核
     *
     * @param orderId
     * @return
     */
    public boolean orderCheckPass(Integer orderId) {
        QueryWrapper<OrderGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0).eq("verify_status", 1).eq("order_id", orderId);
        return orderGoodsMapper.selectCount(queryWrapper) == 0;
    }

    /**
     * 获取所有供应商
     *
     * @return
     */
    public List<JmSupplierResponse> getSupply() {
        ResponseResult<List<JmSupplierResponse>> responseResult = iJmSupplierService.list();
        List jmSupplierResponses = responseResult.getData();
        List<JmSupplierResponse> result = new ArrayList<>();
        for (Object object : jmSupplierResponses) {
            JmSupplierResponse jmSupplierResponse = JSON.parseObject(JSON.toJSONString(object), JmSupplierResponse.class);
            result.add(jmSupplierResponse);
        }
        return result;
    }

    /**
     * 计算订单状态，当数据库订单状态为待收货时调用
     *
     * @param
     * @return
     */
//    public String orderStatus(Integer orderId) {
//        QueryWrapper<OrderGoods> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("del_flag", 0).eq("order_id", orderId);
//        List<OrderGoods> list = orderGoodsMapper.selectList(queryWrapper);
//        List<Byte> statusList = list.stream().map(OrderGoods::getGoodsStatus).collect(Collectors.toList());
//        if (statusList.contains(LogisticsStatusEnum.PART_SEND.getCode())) {
//            return OrderStatusEnum.READY_TO_RECEIVE.getMessage();
//        } else if (statusList.contains(LogisticsStatusEnum.WAIT_RECEIVE.getCode())) {
//            return OrderStatusEnum.READY_TO_RECEIVE.getMessage();
//        } else if (statusList.contains(LogisticsStatusEnum.CONFIRM_RECEIVE.getCode())) {
//            return OrderStatusEnum.COMPLETED.getMessage();
//        } else {
//            return OrderStatusEnum.READY_TO_SHIP.getMessage();
//        }
//    }

    //    public List<PartialResponse> getPartialShipment(List<Integer> orderIds) {
//        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
//        userOrderQueryWrapper.eq("del_flag", DelFlag.NORMAL);
////        userOrderQueryWrapper.eq("order_status", OrderStatusEnum.READY_TO_RECEIVE.getCode());
//        userOrderQueryWrapper.in("id",orderIds);
//        List<UserOrder> userOrders = userOrderMapper.selectList(userOrderQueryWrapper);
//        List<Integer> order = userOrders.stream().map(UserOrder::getId).collect(Collectors.toList());
//        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
//        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
//        orderGoodsQueryWrapper.in("order_id", order);
//        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
//        List<Integer> result = orderGoods.stream().map(OrderGoods::getOrderId).collect(Collectors.toList());
//        userOrderQueryWrapper = new QueryWrapper<>();
//        userOrderQueryWrapper.in("id", result);
//        userOrderQueryWrapper.eq("del_flag", DelFlag.NORMAL);
//        List<UserOrder> userOrderList = userOrderMapper.selectList(userOrderQueryWrapper);
//        List<PartialResponse> partialResponses = new ArrayList<>();
//        userOrderList.forEach(
//                userOrder -> {
//                    PartialResponse partialResponse = new PartialResponse();
//                    BeanUtils.copyProperties(userOrder, partialResponse);
//                    UserDetailsResponse userDetailsResponse = new UserDetailsResponse();
//                    userDetailsResponse.setNickName(userOrder.getReceiverName());
//                    userDetailsResponse.setAddress(userOrder.getReceiverAddress());
//                    userDetailsResponse.setPhone(userOrder.getReceiverPhone());
//                    partialResponse.setUser(userDetailsResponse);
//                    partialResponse.setOrderStatusString(EnumUtil.getByCode(userOrder.getOrderStatus(),OrderStatusEnum.class).getMessage());
//                    partialResponses.add(partialResponse);
//                }
//        );
//        orderGoodsQueryWrapper = new QueryWrapper<>();
//        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
//        orderGoodsQueryWrapper.in("order_id", result);
//        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
//        //获取全部供应商
//        List<JmSupplierResponse> jmSupplierResponses = getSupply();
//        //获取全部发货仓
//        ResponseResult<List<JmWarehouseResponse>> iJmWarehouseServiceAll = iJmWarehouseService.findAll();
//        List<JmWarehouseResponse> jmWarehouseResponses = iJmWarehouseServiceAll.getData();
//        for (PartialResponse partialRespons : partialResponses) {
//            List<PartialOneResponse> partialOneResponses = new ArrayList<>();
//            for (OrderGoods goods : orderGoodsList) {
//                if (partialRespons.getId().equals(goods.getOrderId())) {
//                    if (goods.getGoodsStatus().equals(LogisticsStatusEnum.WAIT_SEND.getCode()) || goods.getGoodsStatus().equals(LogisticsStatusEnum.PART_SEND.getCode())) {
//                        PartialOneResponse partialOneResponse = new PartialOneResponse();
//                        AfterSaleStatusEnum afterSaleStatusEnum = EnumUtil.getByCode(goods.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
//                        partialOneResponse.setAfterSealStatusString(afterSaleStatusEnum.getMsg());
//                        BeanUtils.copyProperties(goods, partialOneResponse);
//                        LogisticsStatusEnum logisticsStatusEnum = EnumUtil.getByCode(goods.getGoodsStatus(), LogisticsStatusEnum.class);
//                        partialOneResponse.setGoodsStatusString(logisticsStatusEnum.getMsg());
//                        if (goods.getSelfFlag() == SelfFlagEnum.YES_SELF.getCode()) {
//                            if (goods.getRealWarehouse() != null) {
//                                partialOneResponse.setSupplierId(goods.getRealWarehouse());
//                                for (JmWarehouseResponse jmWarehouseRespons : jmWarehouseResponses) {
//                                    if (goods.getRealWarehouse().equals(jmWarehouseRespons.getWarehouseId().intValue())) {
//                                        partialOneResponse.setSupplierName(jmWarehouseRespons.getWarehouseName());
//                                    }
//                                }
//                            }
//                        } else if (goods.getSelfFlag() == SelfFlagEnum.NO_SELF.getCode()) {
//                            if (goods.getSupplierId() != null) {
//                                partialOneResponse.setSupplierId(goods.getShouldWarehouse());
//                                for (JmSupplierResponse jmSupplierResponse : jmSupplierResponses) {
//                                    if (goods.getSupplierId().equals(jmSupplierResponse.getSupplierId().intValue())) {
//                                        partialOneResponse.setSupplierName(jmSupplierResponse.getSupplierCompanyName());
//                                    }
//                                }
//                            }
//                        }
//                        partialOneResponses.add(partialOneResponse);
//                    }
//                }
//            }
//            partialRespons.setPartialOneResponses(partialOneResponses);
//        }
//        return partialResponses;
//    }
    public TableDataInfo<PartialResponse> getPartialShipment(PartialRequest request) {


        TableDataInfo<PartialResponse> partialResponseTableDataInfo = new TableDataInfo<>();
        boolean a = false;
        List<Integer> goodsIds = new ArrayList<>();
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        if (request.getType() != null && request.getType().equals(SupplierTypeEnum.SUPPLIER.getCode())) {
            orderGoodsQueryWrapper.eq("supplier_id", request.getSupplierId());
            a = true;
        } else if (request.getType() != null && request.getType().equals(SupplierTypeEnum.DELIVERY_WAREHOUSE.getCode())) {
            orderGoodsQueryWrapper.eq("real_warehouse", request.getSupplierId());
            a = true;
        }
        if (request.getGoodsName() != null) {
            orderGoodsQueryWrapper.like("goods_name", request.getGoodsName());
            a = true;
        }
        if (a) {
            List<OrderGoods> orderFind = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
            goodsIds = orderFind.stream().map(OrderGoods::getOrderId).collect(Collectors.toList());
            if (goodsIds.size() == 0) {
                return partialResponseTableDataInfo;
            }
        }
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
//        if (request.getOrderNo() != null) {
//            userOrderQueryWrapper.like("order_no", request.getOrderNo());
//        }
//        if (request.getStartTime() != null && request.getEndTime() != null) {
//            userOrderQueryWrapper.between("create_time", request.getStartTime(), request.getEndTime());
//        }
//        if (goodsIds.size() != 0) {
//            userOrderQueryWrapper.in("id", goodsIds);
//        }
        List<Integer> findLastOrderIds = userOrderMapper.getPartialShipmentOrderId(request.getOrderNo(), request.getStartTime(), request.getEndTime(), goodsIds.stream().map(i -> i.toString()).collect(Collectors.joining(",")));
//        List<Integer> findLastOrderIds = userFind.stream().map(UserOrder::getId).collect(Collectors.toList());
        if (findLastOrderIds.size() == 0) {
            return partialResponseTableDataInfo;
        }
        //商品
        orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        orderGoodsQueryWrapper.in("order_id", findLastOrderIds);
        orderGoodsQueryWrapper.eq("goods_status", LogisticsStatusEnum.PART_SEND.getCode()).or().eq("goods_status", LogisticsStatusEnum.WAIT_SEND.getCode());
        orderGoodsQueryWrapper.and(
                qw -> qw.in("order_id", findLastOrderIds)
        );
        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        List<Integer> goodsOrderIds = orderGoods.stream().map(OrderGoods::getOrderId).collect(Collectors.toList());
        //订单
        if (goodsOrderIds.size() == 0) {
            return partialResponseTableDataInfo;
        }
        userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.eq("order_status", OrderStatusEnum.READY_TO_RECEIVE.getCode());
        userOrderQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        userOrderQueryWrapper.in("id", goodsOrderIds);
        List<UserOrder> userOrders = userOrderMapper.selectList(userOrderQueryWrapper);
        List<Integer> userOrderIds = userOrders.stream().map(UserOrder::getId).collect(Collectors.toList());
        if (userOrderIds.size() == 0) {
            return partialResponseTableDataInfo;
        }
        //商品
        orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        orderGoodsQueryWrapper.in("order_id", userOrderIds);
        orderGoodsQueryWrapper.eq("goods_status", LogisticsStatusEnum.PART_SEND.getCode()).or().eq("goods_status", LogisticsStatusEnum.WAIT_RECEIVE.getCode());
        orderGoodsQueryWrapper.and(
                queryWrapper -> queryWrapper.in("order_id", userOrderIds)
        );
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        List<Integer> orderIds = orderGoodsList.stream().map(OrderGoods::getOrderId).collect(Collectors.toList());
        //分页订单
        if (orderIds.size() == 0) {
            return partialResponseTableDataInfo;
        }
        userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        userOrderQueryWrapper.in("id", orderIds);
        userOrderQueryWrapper.orderByDesc("create_time");
        IPage<UserOrder> userOrderIPage = new Page<>(request.getPageNum(), request.getPageSize());
        userOrderIPage = userOrderMapper.selectPage(userOrderIPage, userOrderQueryWrapper);
        //获取全部供应商
        List<JmSupplierResponse> jmSupplierResponses = getSupply();
        Map<Integer, JmSupplierResponse> jmSupplierResponseMap = jmSupplierResponses.stream().collect(Collectors.toMap(s -> s.getSupplierId().intValue(), s -> s));
        //获取全部发货仓
        ResponseResult<List<JmWarehouseResponse>> iJmWarehouseServiceAll = iJmWarehouseService.findAll();
        List<JmWarehouseResponse> jmWarehouseResponses = iJmWarehouseServiceAll.getData();
        Map<Integer, JmWarehouseResponse> jmWarehouseResponseMap = jmWarehouseResponses.stream().collect(Collectors.toMap(jmWarehouseResponse -> jmWarehouseResponse.getWarehouseId().intValue(), s -> s));
        //商品
        orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        orderGoodsQueryWrapper.ne("goods_status", LogisticsStatusEnum.WAIT_RECEIVE.getCode());
        orderGoodsQueryWrapper.in("order_id", orderIds);
        orderGoodsQueryWrapper.orderByDesc("create_time");
        List<OrderGoods> goodsList = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        List<PartialResponse> partialResponses = new ArrayList<>();
        userOrderIPage.getRecords().forEach(
                userOrder -> {
                    PartialResponse partialResponse = new PartialResponse();
                    BeanUtils.copyProperties(userOrder, partialResponse);
                    partialResponse.setCreateTime(DateUtil.getTime(userOrder.getCreateTime()));
                    partialResponse.setPayTime(DateUtil.getTime(userOrder.getPayTime()));
                    UserDetailsResponse userDetailsResponse = new UserDetailsResponse();
                    userDetailsResponse.setNickName(userOrder.getReceiverName());
                    userDetailsResponse.setPhone(userOrder.getReceiverPhone());
                    userDetailsResponse.setAddress(userOrder.getReceiverAddress());
                    partialResponse.setUser(userDetailsResponse);
                    partialResponse.setOrderStatusString(EnumUtil.getByCode(userOrder.getOrderStatus(), OrderStatusEnum.class).getMessage());
                    partialResponses.add(partialResponse);
                }
        );
        for (PartialResponse partialRespons : partialResponses) {
            List<PartialOneResponse> partialOneResponses = new ArrayList<>();
            for (OrderGoods goods : goodsList) {
                if (partialRespons.getId().equals(goods.getOrderId())) {
                    PartialOneResponse partialOneResponse = new PartialOneResponse();
                    BeanUtils.copyProperties(goods, partialOneResponse);
                    AfterSaleStatusEnum afterSaleStatusEnum = EnumUtil.getByCode(goods.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
                    partialOneResponse.setAfterSealStatusString(afterSaleStatusEnum.getMsg());
                    BeanUtils.copyProperties(goods, partialOneResponse);
                    LogisticsStatusEnum logisticsStatusEnum = EnumUtil.getByCode(goods.getGoodsStatus(), LogisticsStatusEnum.class);
                    partialOneResponse.setGoodsStatusString(logisticsStatusEnum.getMsg());
                    if (goods.getSelfFlag() == SelfFlagEnum.YES_SELF.getCode()) {
                        if (goods.getRealWarehouse() != null) {
                            partialOneResponse.setSupplierId(goods.getRealWarehouse());
//                            for (JmWarehouseResponse jmWarehouseRespons : jmWarehouseResponses) {
//                                if (goods.getRealWarehouse().equals(jmWarehouseRespons.getWarehouseId().intValue())) {
                            if (jmWarehouseResponseMap.containsKey(goods.getRealWarehouse())) {
                                partialOneResponse.setSupplierName(jmWarehouseResponseMap.get(goods.getRealWarehouse()).getWarehouseName());
                            }
//                                }
//                            }
                        }
                    } else if (goods.getSelfFlag() == SelfFlagEnum.NO_SELF.getCode()) {
                        if (goods.getSupplierId() != null) {
                            partialOneResponse.setSupplierId(goods.getSupplierId());
//                            for (JmSupplierResponse jmSupplierResponse : jmSupplierResponses) {
//                                if (goods.getSupplierId().equals(jmSupplierResponse.getSupplierId().intValue())) {
                            if (jmSupplierResponseMap.containsKey(goods.getSupplierId())) {
                                partialOneResponse.setSupplierName(jmSupplierResponseMap.get(goods.getSupplierId()).getSupplierCompanyName());
                            }

//                                }
//                            }
                        }
                    }
                    partialOneResponses.add(partialOneResponse);
                }
            }
            partialRespons.setPartialOneResponses(partialOneResponses);
        }
        partialResponseTableDataInfo.setRows(partialResponses);
        partialResponseTableDataInfo.setTotal(userOrderIPage.getTotal());
        return partialResponseTableDataInfo;
    }
}
